Python3

Python1-环境配置
Python2-基础认识
Python3-数据类型
Python4-面向对象
Python5-闭包和装饰器
Python6-IO模块
Python7-进程线程携程
Python8-网络编程
Python爬虫

Python编程思想

LEGB规则

Local     指的是函数或者类的方法内部
Enclosed  指的是嵌套函数(一个函数包裹着另一个函数,闭包)
Global    指的是模块中的全局变量
Built in  指的是Python为自己保留的特殊名称

面向过程:找动词

举例:自己开车

面向对象:找名词

举例:造车

Python注释

python的注释大概算做是有两种写法

  1. 单行注释写法

    print('你好呀') # 输出
    
  2. 多行注释写法(误),这是一种写法,用来在函数当中书写文档使用,可以参考大型库的源文件,当然也可以直接作为注释进行使用。

    ‍```
    这是一个注释
    这个注释可以写很多行
    ‍```
    """
    这样也是可以的
    """
    print('你好呀')
    

命名规范

python的命名规则很多,怎么命名都对除了首个字符为数字的形式。

我一般这样命名

├─OneTwo
  	├─three-four.py ──class FiveSix(object) ── def seven_eight() ── nineTen  = 'a'
 	├─three-four.py ──class FiveSix(object) ── def sevenEight() ----nine_ten = 'a'
 	└─three-four.py ──class FiveSix(object) ── def seven_eight() ----NINE_TEN = 'a'

python的转义字符

  1. 续写符 \

    print("line1 \
     line2 \
     line3") # line1 line2 lin3 
    
  2. 反斜杠符号 \\

    print("\\") # \
    
  3. 单引号 '

    print('\'') # '
    
  4. 双引号 "

    print("\"") # "
    
  5. 响铃 \a

    # 执行后电脑有响声。 
    # (windows平台上pycharm终端不会响,要用cmd终端或者pycharm的Terminal终端)
    print("\a") 
    
  6. 退格 \b

    print("Hello \b World!") # Hello World!
    
  7. 空 \000

    # 在不同终端效果不同,windows平台上cmd终端和pycharm的Terminal终端可以看到以下效果
    print("\000")
    
  8. 换行 \n

    print("\n")
    
  9. 纵向制表符 \v

    # 在不同终端效果不同,windows平台上pycharm的Terminal终端可以看到以下效果
    print("Hello \v World!")
    # Hello
    #     World!
    
  10. 横向制表符 \t

    print("Hello \t World!") # Hello    World!
    
  11. 回车 \r

    # 将 \r 后面的内容移到字符串开头,并逐一替换开头部分的字符,直至将 \r 后面的内容完全替换完成。
    # 在不同终端效果不同,windows平台上cmd终端可以看到以下效果
    print("Hello\rWorld!") # World!
    print('google runoob taobao\r123456') # 123456 runoob taobao
    
  12. 换页 \f

    # 在不同终端效果不同,windows平台上pycharm的Terminal终端可以看到以下效果
    print("Hello \f World!")
    # Hello
    #     World!
    
  13. 八进制 \yyy

    # y 代表 0~7 的字符,例:\110 代表大写字母H。
    print("\110\145\154\154\157\40\127\157\162\154\144\41") # Hello World!
    
  14. 十六进制 \xyy

    # 以 \x 开头,y 代表的字符,例:\x48 代表大写字母H。
    print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21") # Hello World!
    

基础学习

变量类型

使用type()查看类型

name = '张三' 
age = 20 
print(name,type(name),age,type(age)) # 张三 <class 'str'> 20 <class 'int'>

转换类型

a = 128
sa = "129"
b = 198.8
sb = "77.77"
c = False
s1 = "hello"
print(a,type(a),sa,type(sa),b,type(b),sb,type(sb),c,type(c),s1,type(s1)) # 128 <class 'int'> 129 <class 'str'> 198.8 <class 'float'> 77.77 <class 'str'> False <class 'bool'> hello <class 'str'>
#  数字类型的和布尔类型的转换成str类型
print(str(a),type(str(a)),str(b),type(str(b)),str(c),type(str(c))) # 128 <class 'str'> 198.8 <class 'str'> False <class 'str'>
# 字符串类型的和布尔类型的转换成int类型
# 将str类型的转成int类型的报错,是因为转换的字符串必须是数字串(正数)
# print(int(sb),type(int(sb)),int(s1),type(int(s1)))
print(int(sa),type(int(sa)),int(c),type(int(c))) # 129 <class 'int'> 0 <class 'int'>
# 字符串类型的/数字类型的和布尔类型的转换成float类型
print(float(a),type(float(a)),float(sa),type(float(sa)),float(c),type(float(c))) # 128.0 <class 'float'> 129.0 <class 'float'> 0.0 <class 'float'>
# 字符转换利用例子
present = input('大圣想要什么礼物呢?') # a
print(present,type(present)) # a <class 'str'>

a = int(input('请输入一个加数')) # 3
# a = int(a)
b = int(input('请输入另一个加数')) # 4
# b = int(b)
print(type(a),type(b)) # <class 'int'> <class 'int'>
print(a+b) # 7

类型判断

if isinstance(money,int):
	True
else:
	False

垃圾回收机制

不需要自己做 python会自动帮助回收 一直扫描

运算符

print('+:', 1+1, '-:', 1-1, '*:', 2*2, '/:', 1/2, '%:', 11%2, '**:', 2**2, '//:', 9//4) # +: 2 -: 0 *: 4 /: 0.5 %: 1 **: 4 //: 2
# 一正一负向下取整
print(-9//-4 , 9//-4 , -9//4) # 2 -3 -3 
# 一正一负公式 余数=被除数-除数*商 9-(-4)*(-3)
print(9%-4 , -9%4) # -3 3

运算判断

通常情况下算数运算:

  1. 先算乘除再算加减
  2. 位运算
  3. 比较运算:运算结果为true或者false
  4. 布尔运算
  5. 赋值运算符
  6. 有括号先算括号内的

赋值运算符从右到左

i = 3+4 
print(i) # 7

链式赋值

# 一个整数对象多次引用
a=b=c=20 
print(a,id(a),b,id(b),c,id(c)) # 20 140729059874184 20 140729059874184 20 140729059874184

参数赋值

a = 20
print(a) # 20
a += 30
print(a) # 50
a -= 10
print(a) # 40
a *= 2
print(a) # 80
a /= 3
print(a) # 26.666666666666668
a //=2
print(a) # 40
a %= 3
print(a) # 2

系列解包赋值

a,b,c = 20,30,40
print(a,b,c,id(a),id(b),id(c)) # 20 30 40 140729059874184 140729059874504 140729059874824

交换两个变量的值

a,b = 10,20
print('交换前',a,b) # 交换前 10 20
a,b=b,a
print('交换之后',a,b) # 交换之后 20 10
a,b = 10,20
print('a>b么?',a>b) # a>b么? False
print('a<b么?',a<b) # a<b么? True
print('a<=b么?',a<=b) # a<=b么? True
print('a>=b',a>=b) # a>=b False
print('a==b',a==b) # a==b False
print('a!=b',a!=b) # a!=b True

比较运算

一个 = 为赋值运算符,两个 == 为比较运算符

一个变量由三部分组成(表示/类型/值)

== 比较的是值

比较对象的标识使用 is

a = 10
b = 10
print(a==b)#True 说明a与b的value相等
print(a is b)#True 说明a与b的id标识相等
print(id(a),id(b))
lst1 = [11,22,33,44]
lst2 = [11,22,33,44]
print(lst1 == lst2)
print(lst1 is lst2)
print(id(lst1),id(lst2))
print(a is not b) #False 错(a的id与b的id是不相等的)
print(lst1 is not lst2) #True 1和2id不相等

is None和 == None的区别

布尔运算

a,b = 1,2
print(a == 1 and b == 2) # True   true and true-->true
print(a == 1 and b < 2) # False   true and false-->false
print(a != 1 and b == 2) # False  false and true-->false
print(a != 1 and b != 2) # False  false and false-->false
print(a == 1 or b == 2) # True   true and true-->true
print(a == 1 or b < 2) # True   true and false-->true
print(a != 1 or b == 2) # true  false and true-->true
print(a != 1 or b != 2) # False  false and false-->false
print(0 << 1) # 0
# 对布尔类型取反
f = True
f2 = False
print(not f) # False
print(not f2) # True

字符串

字符串驻留机制

符串驻留机制优点:

创建和销毁字符串需要时间,驻留机制不需要频繁创建和销毁

用法:

在进行字符串拼接的时候用str类型的join而非+,因为join()效率高

交互模式下测试

>>> s1 = ''
>>> s2 = ''
>>> s1 is s2
True          #驻留机制

>>> s1 = '%'
>>> s2 = '%'
>>> s1 is s2
True          #驻留机制

>>> s1 = 'abc%'
>>> s2 = 'abc%'
>>> s1 == s2
True          #比较的字符相同

>>> s1 is s2
False         #无驻留机制

>>> id(s1)
2231686348464

>>> id(s2)
2231686348528 #id不同

>>> s1 = 'abc%'
>>> s2 = 'abc%'
>>> s1 is s2
False         #无驻留机制因为有"%"特殊字符

>>> s1 = 'abcx'
>>> s2 = 'abcx'
>>> s1 is s2
True          #驻留机制

>>> a = 'abc'
>>> b = 'ab'+'c'
>>> c = ''.join(['ab','c'])
>>> a is b
True

>>> a is c
False         #驻留机制只在编译的时候进行而非运行的时候如:a is b,a is c

>>> c
abc

>>> type(c)
<class 'str'>

>>> a =-5
>>> b =-5
>>> a is b
True

>>> a = -6
>>> b = -6
>>> a is b
False         #驻留机制只在[-5,256]之间的整数数字内存在

>>> import sys
>>> a = 'abc%'
>>> b = 'abc%'
>>> a is b
False

>>> a = sys.intern(b)
>>> a is b
True          #用sys.intern()强制指向

字符优化(pycharm中)

s1 = 'abc%'
s2 = 'abc%'
print(s1 is s2) # True

字符串查找

index和rindex如果子串不存在的时候报错,

find和rfind如果字串不存在的话返回-1,不报错,最好用find和rfind

s = 'hello,world'
print(s.index('lo'))  # 3 第一个lo的位置
print(s.rindex('lo'))  # 3 最后一个lo的位置
print(s.find('lo'))  # 3 第一个lo的位置
print(s.rindex('lo'))  # 3 最后一个lo位置
print(s.find('k')) # -1
print(s.rfind('k')) # -1

字符串大小写转换

运行转换后会产生一个新的字符串

s = 'hello,python'
a = s.upper()  # 全变大写
print(a, id(a)) # HELLO,PYTHON 2995633972784
print(s, id(s)) # hello,python 2995636359920
b = s.lower()  # 全边小写
print(b, id(b)) # hello,python 2995634094832
print(s, id(s)) # hello,python 2995636359920
print(b == s, b is s) # True False
s2 = 'hello,pYthon'
print(s2.swapcase())  # HELLO,PyTHON 大写变小写,小写变大写
print(s2.title())  # Hello,Python 第一个变大写,其余变小写

字符串对齐

居中对齐

# 居中对齐第一个函数指定宽度,第二个函数指定填充内容(默认空格)
s = 'hello,Python'
print(s.center(20, '*'))  # ****hello,Python****

左对齐

s = 'hello,Python'
# 左对齐第一个函数指定宽度,第二个函数指定填充内容
print(s.ljust(20, '*'))  # hello,Python********
# 设定宽度小于字符串,返回原字符
print(s.ljust(10, '*'))  # hello,Python
# 默认填充空格
print(s.ljust(20))  # hello,Python

右对齐

s = 'hello,Python'
 # 右对齐第一个函数指定宽度,第二个函数指定填充内容
print(s.rjust(20, '*'))  # ********hello,Python
# 设定宽度小于字符串,返回原字符
print(s.rjust(10, '*'))  # hello,Python
# 默认填充空格
print(s.rjust(20))  #         hello,Python

s = 'hello,Python'
# 右对齐只能设定一个函数用于指定宽度,用'0'进行填充
print(s.zfill(20))  # 00000000hello,Python
# 设定宽度小于字符串,返回原字符
print(s.zfill(10))  # hello,Python
# 特殊使用
print('-8910'.zfill(8))  # -0008910

字符串分割

s = 'hello world Python'
s1 = 'hello|world|Python'
# 默认以空格做分割符
print(s.split()) # 'hello', 'world', 'Python']
# 认定空格
print(s1.split()) # ['hello|world|Python']
# 以sep指定的字符做为分割符
print(s1.split(sep='|')) # ['hello', 'world', 'Python']
# maxsplit指定分割次数
print(s1.split(sep='|', maxsplit=1)) # ['hello', 'world|Python']
# rsplit逆向分割
print(s.rsplit()) # ['hello', 'world', 'Python']
# 同上
print(s1.rsplit(sep='|')) # ['hello', 'world', 'Python']
# 同上
print(s1.rsplit(sep='|', maxsplit=1)) # ['hello|world', 'Python']

字符串判定

# 判定指定字符串是否为合法标识符
s = 'hello,python'
print('1', s.isidentifier()) # 1 False
print('2', 'hello'.isidentifier()) # 2 True
print('3', '张三'.isidentifier()) # 3 True
print('4', '张三_123'.isidentifier()) # 4 True

# 判定指定字符串是否全部由空白字符组成(回车、换行、水平制表符)
print('5', '\t'.isspace()) # 5 True

# 判断指定的字符串是否全部由字母组成
print('6', 'abc'.isalpha()) # 6 True
print('7', '张三'.isalpha()) # 7 True
print('8', '张三1'.isalpha()) # 8 False

# 判断指定字符是否全部由十进制数字组成
print('9', '123'.isdecimal()) # 9 True
print('10', '123四'.isdecimal()) # 0 False
print('11', 'ⅡⅡⅡ'.isdecimal()) # 11 False

# 判断指定字符串是否全部由数字组成
print('12', '123'.isnumeric()) # 12 True
print('13', '123四'.isnumeric()) # 13 True
print('14', 'ⅡⅡⅡ'.isnumeric()) # 14 True

# 判断指定字符串是否全部由字母数字组成
print('15', 'abc1'.isalnum()) # 15 True
print('16', '张三123'.isalnum()) # 16 True
print('17', 'abc!'.isalnum()) # 17 False

字符串替换/合并

替换

s = 'hello,Python,Python,Python'
#2代表最大替换次数
print(s.replace('Python', 'Java',2)) # hello,Java,Java,Python

合并

lst = ['hello', 'Java', 'Python']
print(''.join(lst)) # helloJavaPython
print(','.join(lst)) # hello,Java,Python
t = ('hello', 'Java', 'Python')
print(','.join(t)) # ello,Java,Python
#将Python字符串做为字符串序列进行连接
print('*'.join('Python')) # P*y*t*h*o*n

字符串比较

比较规程:从前向后进行比较,依次比较下去,直到两个字符串出现不相等,其就是比较结果,后续字符不再比较

比较原理:

  1. 两个字符进行比较时,比较的是其原始值(ascll码)
  2. ord可以得到指定字符对应的原始值,
  3. chr可以得到原始值对应的字符
print('apple'>'app') # True
print('apple'>'bnanan') # False

print(ord('a'), ord('b')) # 97 98
print(chr(97), chr(98)) # a b
print(ord('司'), chr(21496)) # 21496 司

'=='与'is'的区别

== 比较的是value is 比较的是id

a = b = 'Python'
c = 'Python'
print(a == b) # True
print(b == c) # True
print(a == c) # True
print(a is b) # True
print(b is c) # True
print(a is c) # True
print(id(a), id(b), id(c)) # 140729523594064 140729523594064 140729523594064

字符串切片

s = 'hello,Python'
s1 = s[:5]#没有指定起始位置从0开始
s2 = s[6:]#没有指定结束位置到最后一个
s3 = '!'

newstr = s1+s3+s2
print(s1) # hello
print(s2) # Python
print(newstr) # hello!Python
print(id(s), id(s1), id(s2), id(s3)) # 3051173367728 3051172922032 3051173373488 140729524893952
print(id(newstr)) # 3051173501296

#[start:end:stop]从2开始截到5步长为1
print(s[1:5:1]) # ello
#默认从0开始,默认到最后一个元素,步长为2,;两个元素之前的索引间隔为2
print(s[::2]) # hloPto
#默认从最后一个元素开始,到第一个元素结束,因为步长为负数
print(s[::-1]) # nohtyP,olleh
print(s[-6::1]) # Python

字符串格式化

%做占位符

name = '张三'
age = 20
print('我叫%s,今年%d岁' % (name, age)) # 我叫张三,今年20岁

# %宽度精度设置
print('%d' % 3.1415926) # 3
#10表示宽度
print('%10d' % 3.1415926) #          3
#.3代表精度小数点后三位
print('%.3f' % 3.1415926) # 3.142
#同时使用
print('%10.3f' % 3.1415926) #      3.142
print('{0}'.format(3.1415926)) # 3.1415926
#10表示宽度
print('{0:10}'.format(3.1415926)) #  3.1415926
#.3表示一共三位数
print('{0:.3}'.format(3.1415926)) # 3.14
#.3f表示三位小数
print('{0:.3f}'.format(3.1415926)) # 3.142
#同时使用
print('{0:10.3f}'.format(3.1415926)) #      3.142

{}做占位符.format

print('我叫{0},今年{1}岁'.format(name, age)) # 我叫张三,今年20岁

f-string

print(f'我叫{name},今年{age}岁') # 我叫张三,今年20岁

字符串编码格式

编码

S = '天涯共此时'
print(S.encode(encoding='GBK')) # b'\xcc\xec\xd1\xc4\xb9\xb2\xb4\xcb\xca\xb1'
print(S.encode(encoding='UTF-8')) # b'\xe5\xa4\xa9\xe6\xb6\xaf\xe5\x85\xb1\xe6\xad\xa4\xe6\x97\xb6'

解码

S = '天涯共此时'
byte = S.encode(encoding='utf-8')
print(byte.decode(encoding='utf-8')) # 天涯共此时
byte = S.encode(encoding='gbk')
print(byte.decode(encoding='gbk')) # 天涯共此时

列表

列表创建

lst = [10, 20, 30, 40, 50, 60, 70, 80, 90]
lst2 = [100, 110]
空列表 = []

a = (123, 'asd', 'fgh', '123asd')
a = list(a)
print(a) # [123, 'asd', 'fgh', '123asd']
空列表 = list()

列表的增删改查

# 作用:在列表lst追加一个元素110
# 方法:列表+"."+append(元素)
# 特殊性:添加前后内存id不改变,如果添加列表会将列表做为一个元素添加进入
lst.append(100)
print(lst) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# 特殊性展示
lst.append(lst2)
print(lst) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, [100, 110]]

# 作用:在任意位置添加元素
# 方法:列表+"."+insert(位置,元素)
# 特殊性:同append#
lst.insert(0, 1)
print(lst) # [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, [100, 110]]

# 作用:在列表lst后一次性添加多个元素
# 方法:列表+"."+extend(列表)
lst.extend(lst2)
print(lst) # [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, [100, 110], 100, 110]

# 作用:将lst[1:]后全部替换为lst2的数据
# 方法:列表[start开始位置:stop结束位置]+"="+列表2
# 特殊性:插入的位置由start决定,替换的位置由stop决定,step决定元素插入间隔
lst[1::] = lst2
print(lst) # [1, 100, 110]

# 作用:删除列表中指定元素
# 用法:列表+"."+remove(元素)
# 特殊性:有重复元素只移除第一个元素
lst.remove(1) 
print(lst) # [100, 110]

# 作用:删除指定位置元素
# 用法:列表+"."+pop(位置)
# 特殊性:不指定位置时删除最后一个
lst.pop(1) # 110
print(lst) # [100]

# 作用:删除指定段中的元素
# 用法:列表[start:stop]=[]
# 特殊性:切片删除相当于将指定段替换为空段,或将需要的段选出
lst[1:3] = []
print(lst) # [100]
# 特殊性展示
new_list = lst[1:3]
print(new_list) # []

# 作用:清除列表
lst.clear()
print(lst) # []

# 作用:删除列表
del lst
print(lst) # NameError: name 'lst' is not defined.

# 作用:替换列表lst指定位置2的元素100
# 方法:列表[指定位置]+"="+元素
lst2[1] = 100 
print(lst2) # [100, 100]

# 作用:替换列表lst一段元素
# 方法:列表[start:stop]+"="+[元素]
lst2[1:3] = [100, 200, 300, 400]
print(lst2) # [100, 100, 200, 300, 400]

lst = [10, 20, 30, 40, 50, 60, 70, 80, 90]
# 作用:查lst列表中元素10的位置
# 方法:列表名+"."+index(要查的元素)
print(lst.index(10)) # 0
# 10对应的位置在第0位

# 作用:列出lst对应的元素[::-1]
# 方法:列表名[start开始位置:stop结束位置:step步进]
print(lst[::-1]) # [90, 80, 70, 60, 50, 40, 30, 20, 10]

# 作用:判断10是否在列表lst当中存在
# 方法:要判断的元素+"in"+列表,要判断的元素+"not in"+列表 
print(10 in lst) # True
print(100 not in lst) # True

# 作用:遍历列表lst内所有元素
# 方法:循环列表,使列表内元素进入循环打印
for itme in lst:
   print(itme)
# 10 20 30 40 50 60 70 80 90

列表排序

# 通过指定关键字进行排序,id不变
lst.sort()
print(lst) # [10, 20, 30, 40, 50, 60, 70, 80, 90]
# reverse=False升序可省略
# 降序
lst.sort(reverse=True)
print(lst) # [90, 80, 70, 60, 50, 40, 30, 20, 10]

# 调用内置函数进行排序,id改变
new_list = sorted(lst)
# 升序
desc_list = sorted(lst,reverse=True)
# 降序
print(new_list) # [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(desc_list) # [90, 80, 70, 60, 50, 40, 30, 20, 10]

列表生成式 / 列表推导式

# [表达式  for item in 可迭代对象]
# 或者:[表达式  for item in 可迭代对象 if 条件判断]
lst3 = [i for i in range(1, 9)]
print(lst3) # [1, 2, 3, 4, 5, 6, 7, 8]
lst3 = [i * i for i in range(1, 9)]
print(lst3) # [1, 4, 9, 16, 25, 36, 49, 64]

集合

集合创建

s = {1, 1, 2, 2, 3, 3, 4, 4, 5, 5}  # 集合当中元素不允许重复
print(s) # {1, 2, 3, 4, 5}

s1 = set(range(6))
print(s1, type(s1)) # {0, 1, 2, 3, 4, 5} <class 'set'>

s2 = set([1, 2, 3, 4, 5, 6])
print(s2, type(s2)) # {1, 2, 3, 4, 5, 6} <class 'set'>

s3 = set((1, 2, 3, 4, 5, 6))
print(s3, type(s3)) # {1, 2, 3, 4, 5, 6} <class 'set'>

s4 = set('python')
print(s4, type(s4)) # {'h', 'n', 'p', 'y', 't', 'o'} <class 'set'>

s5 = set({1, 2, 3, 4, 5, 6})
print(s5, type(s5)) # {1, 2, 3, 4, 5, 6} <class 'set'>

s6 = {}  # 花括号直接定义为字典类型
print(s6, type(s6)) # {} <class 'dict'>
空集合 = set()
print(type(空集合)) # <class 'set'>

集合的增删

s.add(100) 
print(s) # {1, 2, 3, 4, 5, 100}

s.update({200, 400, 300})
print(s) # {1, 2, 3, 4, 5, 100, 200, 300, 400}
s.update('123')
print(s) # {1, 2, 3, 4, 5, 100, 200, 300, '1', '2', 400, '3'}
s.update([500, 600])
print(s) # {1, 2, 3, 4, 5, 100, 200, 300, '1', '2', 400, '3', 500, 600}
s.update((700, 800))
print(s) # {800, 1, 2, 3, 4, 5, 100, 200, 300, '1', '2', 400, '3', 500, 600, 700}

s.remove(100)
print(s) # {800, 1, 2, 3, 4, 5, 200, 300, '1', '2', 400, '3', 500, 600, 700}
# s.remove(505)#删除不存在的元素会报错
s.discard(505)  # 删除不存在的元素不会报错
print(s) # {800, 1, 2, 3, 4, 5, 200, 300, '1', '2', 400, '3', 500, 600, 700}
# 删除任意一个数
s.pop() # 800
print(s) # {1, 2, 3, 4, 5, 200, 300, '1', '2', 400, '3', 500, 600, 700}
s.clear()  # 清空集合
print(s) # set()
del s  # 删除一个集合
# 打印地址不存在报错
print(s)  # NameError: name 's' is not defined.

集合的特性 : 因为集合是无序且不重复的。并且集合一旦创建是不能够被修改的。

集合间关系

s = {10, 20, 30, 40, 50, 60}
s2 = {20, 30, 40, 10}
s3 = {10, 20, 90}
s4 = {100, 200, 300}

print(s == s2) # Flase
print(s != s2) # True
'''两个集合是否相等(元素相同就相等)'''

子集

print(s2.issubset(s)) # True
print(s3.issubset(s)) # False

超集

print(s.issuperset(s2)) # True
print(s.issuperset(s3)) # False

交集

print(s2.isdisjoint(s3)) # False
print(s2.isdisjoint(s4)) # True

数学运算

交集

print(s.intersection(s2)) # {40, 10, 20, 30}
print(s & s2) # print(s & s2)

并集

print(s.union(s2)) # {40, 10, 50, 20, 60, 30}
print(s | s2) # {40, 10, 50, 20, 60, 30}

差集

print(s.difference(s2)) # {50, 60}
print(s - s2) # print(s - s2)

对称哈希

print(s.symmetric_difference(s2)) # {50, 60}
print(s ^ s2) # {50, 60}

集合生成式 / 集合推导式

# {表达式 for item in 可迭代对象}
# 或者:{表达式 for item in 可迭代对象 if 条件判断}
s = { i*i for i in range(10)}
print(s) # {0, 1, 64, 4, 36, 9, 16, 49, 81, 25}

字典

字典创建

student = dict(name='jack', age=20)
print(student) # {'name': 'jack', 'age': 20}
空字典 = dict()

scores = {'张三': 100, '李四': 98, '王五': 45}
print(scores) # {'张三': 100, '李四': 98, '王五': 45}
空字典 = {}

字典的增删改查

scores['陈六'] = 98
print(scores) # {'张三': 100, '李四': 98, '王五': 45, '陈六': 98}

del scores['张三']  # 删除指定的key——value键值对
print(scores) # {'李四': 98, '王五': 45, '陈六': 98}
scores.clear()  # 清空字典中的元素
print(scores) # {}

scores['陈六'] = 100
print(scores) # {'陈六': 100}

# 第一种
print(scores['陈六']) # 100
# 第二种
a = scores.get('陈六')
print(a) # 100
print(scores.get('麻七')) # None
print(scores.get('麻七', 99)) # 99
# 区别如果查找不存在的键第一种报错,第二种返回None,99是查找‘麻七’时所对应的value不存在时,提供的一个默认值

查key是否存在

# 查张三这个key是否在字典当中
print('张三' in scores) # False
print('张三' not in scores) # True

获取key

keys = scores.keys()
print(keys) # dict_keys(['陈六'])
# 将获取的key键变成列表
print(list(keys)) # ['陈六']

values = scores.values()
print(values) # dict_values([100])
# 将获取的value键变成列表
print(list(values)) # [100]

items = scores.items()
print(items) # dict_items([('陈六', 100)])
# 将获取的key-value键值对变成列表,()包含的是元组
print(list(items)) # [('陈六', 100)]

字典遍历

for item in scores:
    print(item, scores[item], scores.get(item)) # 陈六 100 100

字典特殊性

#key不能重复但value可以重复
#key必须是不可变对象,(不能是列表)
#字典无序性,不能在指定位置添加内容(因为字典是哈希函数计算储存)
# d = {'name': '张三', 'name': '李四'}
# print(d)
d = {'name': '张三', 'nikename': '张三'}
print(d) # {'name': '张三', 'nikename': '张三'}

字典生成式 / 字典推导式

# {key_expression : value_expression for 表达式 in 可迭代对象 if 条件判读}
items = ['Fruits', 'Books', 'Others']
prices = [96, 78, 86]

d = {item: price for item, price in zip(items, prices)}
print(d) # {'Fruits': 96, 'Books': 78, 'Others': 86}

元组

元组特殊性

不可变序列,可变序列 区别id地址是否发生改变
可变序列: 列表,字典
不可变序列: 字符串,元组

元组创建

t = ('python',)  # 只有一个元素时需要在元素后加上逗号
t0 = ('python', 'world', 98)  
print(type(t)) # <class 'tuple'>
print(t) # ('python',)
空元组 = ()

t2 = 'python', 'world', 98  # 最少两个否则将认定为赋值,为str类型,
print(type(t2)) # <class 'tuple'>
print(t2) # ('python', 'world', 98)

t1 = tuple(('python', 'world', 98))
print(type(t1)) # <class 'tuple'>
print(t1) # ('python', 'world', 98)
空元组 = tuple()

t = (10, [20, 30], 40)
print(t, type(t)) # (10, [20, 30], 40) <class 'tuple'>
print(t[0], type(t[0]), id(t[0])) # 10 <class 'int'> 140729634952264

尝试修改

print(id(100)) # 140729634955144
# t[0] = 100 #元组不允许修改元素
t[1].append(100)  # 元组中的列表可以修改
print(t, id(t)) # (10, [20, 30, 100], 40) 1919938284288

元组遍历

for item in t:
    print(item)
# 10 [20, 30, 100] 40

生成器推导式(用于创建生成器)

一个生成器只能使用一次,用来实现惰性求值

(表达式 for item in 可迭代对象 if 条件判断)
# 第一种
c_genre = (i for i in range(3))

for i in c_genre:
    print(i) # 0 1 2
  
# 第二种
def mygenerater(n):
    for i in range(n):
        print('开始执行')
        yield i
        print('完成一次')
        yield i+2

if __name__ == '__main__':
    g = mygenerater(3)
    print(g) # <generator object mygenerater at 0x000001BF0535B680>
    for i in g:
        print(i) # 开始执行 0 完成一次 2 开始执行 1 完成一次 3 开始执行 2 完成一次 4

# 斐波那契数列
def fibonacci(num):
    a = 0
    b = 1
    current_index = 0

    while current_index <num:
        result = a
        a, b = b, a + b
        current_index += 1
        print(a,b)
        yield result


fib = fibonacci(100)
for value in fib:
    print(value)
posted @ 2025-03-24 18:35  *--_-  阅读(55)  评论(0)    收藏  举报