2023.1.08-09 python基础

列表常用方法

append 增加一个元素

a.append('aaaa')

extend 增加多个

a.extend([1,2,3,4,5,6])

index检索,个人理解类似于find

print(a.index("is"))

inset 指定位置插入

a.insert(2,"aasdfasdf")

pop 删除 把列表中最后一个元素删除,还会把删除的元素返回回来 (基本不怎么用这个)

a.pop()

count计次

a.count('a')
count搭配remove循环删除列表中的某个数
for i in range(a.count(1)):
    a.remove(1)
print(a)

reverse 反转,把列表中的元素反转一下

a.reverse()

sort 排序 这个暂时不会,后面用到来补充

 

元组

感觉基本用不到,列表用的多

a=(1,2,3,34,5,6,7,7)
print(a.count(1))
print(a.index(1))

 

字典

clear 清空

a.clear()
print(a)

get 取出元素

print(a.get('python'))

items 列出键值对

print(a.items())

update 更新

a.update({"python":100})
print(a)
函数

 

类的属性和方法

面向对象,

class testone:
    #共有变量写法
    a = 1
    #私有变量写法
    __a =2
    def test1(self):
        print("内部变量" ,self.__a)

test111 = testone()
test111.test1()
两个循环中常用的方法

enumerate 循环的时候自带计数

items1 =['wahaha','gege','dagege','666']

for i in enumerate(items1):   自带计数,在前面显示
    print(i)

zip 循环的时候合并多个列表

items1 =['wahaha','gege','dagege','666']
ages = [30,40,50,60]
for age,item in zip(ages,items1):
    print(age,item)
文本操作

w只写

r只读

a只写追加

+可读可写

with open('test.txt','r+',encoding='utf-8') as f:
    file = f.readlines()
    for i in file:
        print(i.strip())
args和kwargs解释(这个适合不知道接收多少个参数,用户输入的啥不确定)

 

作为函数参数的时候,*args把用户输入的参数全接受 **kwargs把用户输入的等于格式的参数接收
打印的时候   args 返回元组    kwargs 返回字典

def foo(one,*args,**kwargs):
    print(one)
    print(args)
    print(kwargs)

foo(1,2,3,4,5,6,7,8,9,10,kk=1,ll=9)

闭包和装饰器

1.外函数--内函数

2.外函数返回内函数

3.内函数引用了外函数的变量

初次学习理解为函数内部引用函数外部(还是函数)的变量

def foo():
    onter =10
    def inner():
        print(onter)
        return
    return inner()

res = foo()
print(res)

如果想在内函数修改外函数的变量,加nonlocal关键字声明

def foo():
    onter =10
    def inner():
        nonlocal onter
        onter=10
        print(onter)
        return
    return inner()

res = foo()
print(res)

计时装饰器例子(不会写,没听懂,看书去)

 

异常捕获

try

except

try:
    a =1
    print(b)
except Exception as e:
    print(e)
    print(a)

finally: (一般用不到)

try:
    a =1
    print(b)
except Exception as e:
    print(e)
    print(a)
finally:
    print("无论处不出错,都会执行finally的代码")

自定义报错:

class My(BaseException):
    def __int__(self):
        print("实例化之后会运行")

    def __str__(self):
        return "这是我自定义的类"

raise My

另外一种

import traceback
try:
    a
except Exception as e:
    print(e)
    traceback.print_exc()

如果特别长可以输出到文件

import traceback
try:
    a
except Exception as e:
    print(e)
    traceback.print_exc(file=open('error.txt','a+'))

 

迭代器(2023-1-09没听懂。回去接着听)

第一次接触,类似于for循环个人感觉

这个地方开始有点听不懂了,明天去B站找视频看一下。

 

posted @   猪圈网络安全  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示