六|6.1_4 Python3.x入门 P4 【基础】可变序列(列表list、字典dict、集合set)

相关链接

  • 目录
  • Mac M1 Python环境搭建
  • Python3.x入门 P1 【基础】注释、标识符、变量、数据类型
  • Python3.x入门 P2 【基础】运算符
  • Python3.x入门 P3 【基础】流程语句【循环结构】
  • Python3.x入门 P4 【基础】可变序列(列表list、字典dict、集合set)
  • Python3.x入门 P5 【基础】不可变序列(元组tuple、字符串str)
一、序列 可变序列:可以对执行序列进行增、删、改操作,对象地址不发生改变。
????① 列表list -> [v1,v2,…]、② 集合set -> {k1,k2,…}、③ 字典dict -> {k1:v1,…}
不可变序列:没有增、删、改的操作。由于其不可变特性,在多线程场景下,不需要加锁。
????① 元组tuple -> (v1,v2,…) 、② 字符串str -> ‘’
1.1 可变序列&不可变序列
""" @author GroupiesM @date 2022/6/22 16:11 @introduction 可变序列:列表list、字典dict、集合set 可以对执行序列进行增、删、改操作,对象地址不发生改变 不可变序列:元组tuple、字符串str 没有增、删、改的操作 """ '''可变序列 列表list、字典dict、集合set''' lst = [10, 20, 45] lst.append(300) print(lst)# [10, 20, 45, 300]'''不可变序列 元组tuple、字符串str''' t = ('python', 5) print(t)# ('python', 5)

1.2 不可变序列&多线程
""" @author GroupiesM @date 2022/4/29 09:25 @introduction 不可变序列(元组、字符串)在多个线程场景下,同时操作同一对象时不需要加锁 注意事项: 元组中存储的是对象的引用 a) 如果元组中对象本身不可变对象,即指向的内存地址不可变 b) 如果元组中的对象是非基本类型,可以修改其中的数据 """ t = (10, [20, 30], 9) print(t)# (10, [20, 30], 9)'''元组中的元素是引用类型时,可以修改引用类型的数据''' t[1].remove(30)# (10, [20], 9) print(t)# (10, [20], 9)'''不可以修改元素的内存地址''' t[1] = [50] print(t)# TypeError: 'tuple' object does not support item assignment

1.3 总结
数据结构 可变序列 值可重复 是否有序 定义符号
列表(list) [v1,v2,…]
集合(set) × × {k1,k2,…}
字典(dict) key(×) value(√) × {k1:v1,k2:v2,…}
元组(tuple) × (v1,v2,…)
P.S:
??1.不可变序列在内存中是不会改变的
??2.如果对不可变序列做出改变,会将该序列存储在新的地址空间中,而原来的序列因为垃圾回收机制,会被回收。
??3.可变序列发生改变时,是不会改变地址的,而是改变内存中的值,或者是扩展内存空间。
??4.字典是一个可变序列,但是字典的键是不可变的,而值是可变的。因为字典结构的原理是伪随机探测的散列表,它的查找方式是将键通过哈希函数,找到值的内存地址。所以哈希后的值一般是唯一的或是冲突比较小的。如果改变键的值,name哈希后的值就会发生变化,导致找不到原来的值,所以键的值是不可变的。键哈希后指向的是内存中的地址,内存中的数据发生变化不影响字典的查找。
二、列表list -> [v1,v2,…] 2.1 简介
""" @author GroupiesM @date 2022/4/28 09:26 @introduction 列表:list = ['hello', 'world', 100] 集合: set= {'python', 'hello', 90} 字典:dict = {'name': '张三', 'age': 100} 元组:tuple = ('python','hello',90) 字符串: str = 'python' """ lst = ['hello', 'world', 100] print(type(lst))# print(lst)# ['hello', 'world', 100]

2.2 创建
""" @author GroupiesM @date 2022/4/28 09:36 @introduction列表创建方式: 方式一:使用中括号[],元素之间英文逗号分隔 list = ['hello','python'] 方式二:内置函数 list() 类型转换 list(('hello','php'))# list -> list list({'name': '张三', 'age': 100})# 字典 -> list list(['hello','php'])# 元组 -> list list({'python', 'hello', 90})# 集合 -> list list('hello')# 字符串->list """ '''方式一''' lst = ['hello', 'python', 13] print(lst)# ['hello', 'python', 13]'''方式二''' '''1.list->list''' lst1 = list(('hello', 'php'))# list -> list print('lst1', lst1) # ['hello', 'php']'''2.字典->list时,自动取字典的key''' lst2 = list({'name': '张三', 'age': 100})# 字典 -> list print('lst2', lst2) # ['name', 'age']'''3.元组->list''' lst3 = list(['hello', 'php'])# 元组 -> list print('lst3', lst3) # ['hello', 'php']'''4.集合->list''' lst4 = list({'python', 'hello', 90})# 集合 -> list print('lst4', lst4) # [90, 'python', 'hello']'''5.字符串->list''' lst5 = list('hello')# 字符串->list print('lst5', lst5) # ['h', 'e', 'l', 'l', 'o']

2.3 特点
""" @author GroupiesM @date 2022/4/28 09:41 @introduction 1.元素有序 2.每个索引映射唯一数据 3.值可重复 4.任意数据类型混合存储 5.根据需要动态分配和回收内存 6.基本类型:值相同时,内存地址一样 7.引用类型:值相同时,内存地址不一样P.S len()获取对象长度,不能用于int,float,bool类型 """ list = ['hello', 'hello', ['张三', '李四'], ['张三', '李四'], 50, True] print(len(list))# 5 for i in range(0, len(list)): print(list[i], end="\t") '''hello hello ['张三', '李四'] ['张三', '李四'] 50 True ''' print()for i in range(0, len(list)): print(id(list[i]), end="\t") ''' hello出现了两次,两次的id都是4310643824 ['张三', '李四']:两次出现,id却不同 4310643824 4310643824 4312636928 4312643456 4321732376 4321512264 '''

2.4 list[n] 查找 索引 -> 值
""" @author GroupiesM @date 2022/4/28 10:10 @introduction索引->值: 正向索引从0到n-1 list[0] -> list[n-1] 逆向索引从-n到-1 list[-n] -> list[-1] 指定索引不存在,抛出IndexError """ list = ['hello', 'python', 'python', 50, True]print('--------正向索引遍历--------') for i in range(0, len(list)): print(list[i], end="\t") # # hello python python 50 Trueprint('\n--------逆向索引遍历--------') for i in range(-len(list), 0, 1): print(list[i], end="\t")# hello python python 50 True

2.5 list.index() 查找 值 -> 索引
""" @author GroupiesM @date 2022/4/28 09:55 @introductionindex(): 如果列表中存在n个相同元素,只返回相同元素中第一个元素索引 如果查询的元素在列表中不存在,则会抛出ValueError 还可以指定的start,stop索引范围内查找 """list = ['hello', 'python', 'python', 50, True] ''' index:01234 ['hello', 'python', 'python', 50, True] '''num: int = list.index('python') print(num) '''1'''num: int = list.index(50) print(num) '''3'''num: int = list.index('50') print(num) '''ValueError: '50' is not in list'''

2.6 切片 -> 获取新列表
""" @author GroupiesM @date 2022/4/28 10:15 @introduction 获取列表中的多个元素 语法格式: 列表名[start:stop:step] 切片操作: 切片的结果:原列表切片,形成新的列表 切片的范围:[start,stop) step默认为1:简写为[start:stop] step为正数:从start开始往后计算切片 [:stop:step]:切片的第一个元素默认是列表的第一个元素 [start::step]:切片的最后一个元素默认是列表的最后一个元素 step为负数:从start开始往前计算切片 [:stop:step]:切片的第一个元素默认是列表的最后一个元素 [start::step]:切片的最后一个元素默认是列表的第一个元素 """ #0123456789正向索引 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #-9 -8 -7 -6 -5 -4 -3 -2 -10逆向索引'''索引长度''' print(len(list))# 10'''step默认为1''' print(list[1:8])# [2, 3, 4, 5, 6, 7, 8] print(list[1:-2])# [2, 3, 4, 5, 6, 7, 8]'''step为正数''' print(list[:10:2])# [1, 3, 5, 7, 9] print(list[0::2])# [1, 3, 5, 7, 9]'''step为负数数''' print(list[:-10:-2])# [10, 8, 6, 4, 2] print(list[10::-2])# [10, 8, 6, 4, 2]

2.7 判断 in¬ in
""" @author GroupiesM @date 2022/4/28 11:12 @introduction 判断指定元素在列表中是否存在 元素 in 列表名 元素 not in 列表名 """ list = [10, 20, 30, 40]print('p' in 'python')# True print(10 in list)# True print(15 in list)# False print('abc' not in list)# True

2.8 遍历
""" @author GroupiesM @date 2022/4/28 11:30 @introduction 列表元素的遍历 for 迭代遍历 in 列表名 操作 """list = [1, 2, 3, 4] print("----方式一------")for i in list: print(i, end="\t")# 1 2 3 4print("\n----方式二------") for i in range(len(list)): print(list[i], end="\t")# 1 2 3 4

2.9 添加4种方式 【六|6.1_4 Python3.x入门 P4 【基础】可变序列(列表list、字典dict、集合set)】1. append(Object obj):在列表末尾添加一个元素。
2. extend(Iterator iter):在列表末尾添加一个元素。(遍历其中所有元素后,添加其中的元素)
3. insert(Integer i,Object obj):在列表的指定位置添加元素。
4. lst[切片]:先对列表切片,再添加ele。lst[start:stop:step]:三个参数均可以不填。
??P.S :Object = 任意类型; Iterator = 迭代器类型
2.9.1 append()-添加元素到末尾
""" @author GroupiesM @date 2022/4/28 11:38 @introduction append(Object obj):在列表末尾添加一个元素。 """ '''添加元素 - 基本类型''' lst = [10, 20, 30] lst.append(40) lst.append(50) print(lst, id(lst))# [10, 20, 30, 40, 50] 4378974400lst重新赋值,id发生改变'''添加元素 - 列表''' lst = [10, 20, 30] tmp = [40, 50] print(lst, id(lst))# [10, 20, 30] 4377304000 lst.append(tmp) print(lst, id(lst))# [10, 20, 30, [40, 50]] 4377304000,id没变,说明还是原来的列表

2.9.2 extend()-遍历元素并添加到末尾
""" @author GroupiesM @date 2022/4/28 11:39 @introduction extend(Iterator iter):在列表末尾添加一个元素。(遍历其中所有元素) """ ''' 添加元素 - 基本类型(x) extend只适用于迭代器类型元素 ''' lst = [10, 20, 30, 40] try: lst.extend(50) except Exception as e: print(e)# 'int' object is not iterable print(lst)''' 添加元素 - 列表(v) 列表属迭代器 ''' lst = [10, 20, 30, 40] tmp = [40, 50] lst.extend(tmp) print(lst)

2.9.3 insert()-添加元素到指定位置
""" @author GroupiesM @date 2022/4/28 13:46 @introduction insert(Integer i,Object obj):在列表的指定位置添加元素。 """ ''' 添加元素 - 基本类型 在索引0的位置添加一个元素 'a' ''' lst = [10, 20, 30] print(lst, id(lst))# [10, 20, 30] 4305885440 lst.insert(0, 'a') print(lst, id(lst))# ['a', 10, 20, 30] 4305885440''' 添加元素 - 列表 在索引0的位置添加一个列表['a','b'] ''' lst = [10, 20, 30] tmp = ['a', 'b'] print(lst, id(lst))# [10, 20, 30] 4305886272 lst.insert(0, tmp) print(lst, id(lst))# [['a', 'b'], 10, 20, 30] 4305886272

2.9.4 切片(并替换)
""" @author GroupiesM @date 2022/4/28 13:33 @introduction lst[切片] = ele:先对列表切片,再添加 1) lst[start:stop:step] = ele : 1.1 替换操作 1.2 被替换的元素数量,和替换的元素数量,要相等 1.3 其中start,stop,step均可以不填,默认值分别为0,len(lst),1 2) lst[start:stop] = ele: 其中start,stop均可以不填,默认值分别为0,len(lst) 2.1 替换操作 2.2 被替换的元素数量,和替换的元素数量,不需要相等 2.3 其中start,stop均可以不填,默认值分别为0,len(lst) 3) lst[start:start] = ele: 在上面的基础上,start和stop值一样,就相当于插入效果区别:第一种方式前后元素数量要一致,第二种方式前后元素数量没有要求 """ ''' 1) 替换操作 [start:stop:step] 从索引0开始,索引每+2进行一次替换操作,一共进行10/2=5次 ''' lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd', 'e'] lst[0:len(lst):2] = tmp print(lst)# ['a', 10, 'b', 30, 'c', 50, 'd', 70, 'e', 90]lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd', 'e'] # lst[::2]等价于 lst[0:len(lst):2] lst[::2] = tmp print(lst)# ['a', 10, 'b', 30, 'c', 50, 'd', 70, 'e', 90] ,与上面测试结果相同,两种写法等价lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd']try: lst[::2] = tmp except Exception as e: print(e) """ attempt to assign sequence of size 4 to extended slice of size 5 尝试将大小为4的序列分配给大小为5的扩展片 """ print(lst)''' 2) 替换操作 [start:stop] 2.1) 将1-end,替换为新数组 2.2) 将0-1,替换为新数组 ''' lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd', 'e']lst[1:] = tmp print(lst)# [0, 'a', 'b', 'c', 'd', 'e']lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd', 'e']lst[1:len(lst)] = tmp print(lst)# [0, 'a', 'b', 'c', 'd', 'e'] ''' 3) 添加操作 [start:start] 3.1) 在索引1的位置插入新数组 ''' lst = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] tmp = ['a', 'b', 'c', 'd', 'e']lst[1:1] = tmp print(lst)# [0, 'a', 'b', 'c', 'd', 'e', 10, 20, 30, 40, 50, 60, 70, 80, 90]

2.10 删除5种方式 1. remove(Object obj):删除指定Value的元素。
??1)一次删除一个元素。
??2)重复元素只删除第一个。
??3)Value不存在则抛出ValueError。
2. pop(Integer i):删除指定index的元素。
??1)指定索引不存在抛出IndexError。
??2)不指定索引,删除列表中最后一个元素。
3. clear( ):清空列表。
4. del lst:删除列表。
5. lst[切片]:对列表切片。
2.10.1 remove()-删除指定Value
""" @author GroupiesM @date 2022/4/28 15:39 @introduction remove(): 删除指定Value的元素 一次删除一个元素 重复元素只删除第一个 Value不存在则抛出ValueError """ lst = [10, 20, 30, 20, 10] lst.remove(10) print(lst)# [20, 30, 20, 10]lst.remove(30) print(lst)# [20, 20, 10]

2.10.2 pop()-弹出指定索引位置
""" @author GroupiesM @date 2022/4/28 15:39 @introduction pop(): 删除指定index的元素 指定索引不存在抛出IndexError 不指定索引,删除列表中最后一个元素 """ lst = [10, 20, 30, 20, 10] lst.pop(1) print(lst)# [10, 30, 20, 10]lst.pop(11)# IndexError: pop index out of range

2.10.3 clear()-清空列表
""" @author GroupiesM @date 2022/4/28 15:39 @introduction clear(): 清空列表 """ lst = [10, 20, 30, 20, 10] lst.clear() print(lst)# []

2.10.4 del lst-删除列表
""" @author GroupiesM @date 2022/4/28 15:39 @introduction del: 删除列表 """ lst = [10, 20, 30, 20, 10] del lst print(lst)# NameError: name 'lst' is not defined

2.10.5 切片
""" @author GroupiesM @date 2022/4/28 15:39 @introduction 切片: 删除指定[范围]的索引 """ lst = [10, 20, 30, 20, 10] lst = lst[::2] # 从0开始,到结尾,index每+2,截取一次 print(lst)# [10, 30, 10]

2.11 修改元素
""" @author GroupiesM @date 2022/4/28 15:47 @introduction 列表元素的修改操作 为指定索引的元素赋值一个新值 为指定的切片赋值一个新值 """ ''' 单值修改 将索引为2的值修改为100 ''' lst = [10, 20, 30, 40] lst[2] = 100 print(lst)# [10, 20, 100, 40]''' 范围修改 将索引 [1-3) 的值修改为200,300,400,500 ''' lst = [10, 20, 30, 40] lst[1:3] = [200, 300, 400, 500] print(lst)# [10, 200, 300, 400, 500, 40]

2.12 排序
""" @author GroupiesM @date 2022/4/28 15:54 @introduction 常见的两种方式 1) 调用sort()方法,列中的所有元素默认按照从小到大的顺序进行排序,可以指定revers=True,进行降序排序 2) 调用内置函数sorted(),可以指定revers=True,进行降序排序区别: sort() 对原列表进行处理 sorted() 返回一个新列表,原列表不发生改变 """ ''' 1) sort排序 指定参数 reverse=True 可以进行倒序排序 调用列表方法 reverse 可以进行反转实现倒序排序 ''' '''1.1 升序排序''' lst = [10, 90, 20, 80, 30, 70] lst.sort() print(lst)# [10, 20, 30, 70, 80, 90]'''1.2 降序排序''' lst = [10, 90, 20, 80, 30, 70] lst.sort(reverse=True)# reverse=True表示降序排序,默认reverse=False print(lst)# [90, 80, 70, 30, 20, 10]'''1.3 降序排序''' lst = [10, 90, 20, 80, 30, 70] lst.sort() lst.reverse() print(lst)# [90, 80, 70, 30, 20, 10]''' 2) sorted排序 ''' print("-------------")'''2.1 升序排序''' lst = [10, 90, 20, 80, 30, 70] n_lst = sorted(lst) print(n_lst)# [10, 20, 30, 70, 80, 90]'''2.2 降序排序''' lst = [10, 90, 20, 80, 30, 70] n_lst = sorted(lst, reverse=True) print(n_lst)# [90, 80, 70, 30, 20, 10]

2.13 列表生成式
""" @author GroupiesM @date 2022/4/28 16:05 @introduction 全称"生成列表的公式" 语法格式: [fx(i) for i in range(n,m)] fx(i): 表达式 i : 自定义变量 range(n,m) : 可迭代对象 注意事项: 表示列表元素的表达式中,通常包含自定义变量 """lst = [i * i for i in range(0,10)] print(lst) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ''' 第一次循环 i=0, i*i = 0 第二次循环 i=1, i*i = 1 第三次循环 i=2, i*i = 4 第四次循环 i=3, i*i = 9 第五次循环 i=4, i*i = 16 '''

2.14 转换-zip->list
""" @author GroupiesM @date 2022/6/22 15:22 @introduction 内置函数zip(): 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回有这些元组组成的列表 key-value数量不一致时,参考短板效应""" items = ['水果', '书本', '鱼缸', '马桶'] prices = [10, 20, 30] zip = zip(items, prices) lst = list(zip) print(type(zip), zip)# print(type(lst), lst)# [('水果', 10), ('书本', 20), ('鱼缸', 30)]

三、集合set -> {k1,k2,…} 3.1 简介&特点 特点
??1) 属可变序列
??2) 自动去重
??3) 集合中元素无序排列
""" @author GroupiesM @date 2022/4/28 17:14 @introduction 列表:list = ['hello', 'world', 100] 集合: set= {'python', 'hello', 90} 字典:dict = {'name': '张三', 'age': 100} 元组:tuple = ('python','hello',90) 字符串: str = 'python' """ s = {'python', 'hello', 90, 90} print(type(s))# print(s) # {90, 'python', 'hello'}

3.2 创建
""" @author GroupiesM @date 2022/4/29 15:21 @introduction 方式一:使用花括号{},元素之间英文逗号分隔 set = {'python', 'hello', 90} 方式二:内置函数 list() 类型转换 set(['hello','php']) # 元组->set set('hello') # 字符串->set集合创建方式: 方式一:使用花括号{},元素之间英文逗号分隔 set = ['hello','python'] 方式二:内置函数 list() 类型转换 set(('hello','php'))# list -> set set({'name': '张三', 'age': 100})# 字典 -> set set(['hello','php'])# 元组 -> set set({'python', 'hello', 90})# 集合 -> set set('hello')# 字符串->set """'''方式一''' s = {'hello', 'python'} print(s)# {'python', 'hello'}'''方式二''' '''1.list->set''' set1 = set(('hello', 'php'))# list -> set print('set1', set1)# {'php', 'hello'}'''2.字典->set时,自动取字典的key''' set2 = set({'name': '张三', 'age': 100})# 字典 -> set print('set2', set2)# {'age', 'name'}'''3.元组->set''' set3 = set(['hello', 'php'])# 元组 -> set print('set3', set3)# {'php', 'hello'}'''4.集合->set''' set4 = set({'python', 'hello', 90})# 集合 -> set print('set4', set4)# {'python', 90, 'hello'}'''5.字符串->set''' set5 = set('hello')# 字符串->set print('set5', set5)# {'h', 'o', 'l', 'e'}

3.3 判断in¬ in
""" @author GroupiesM @date 2022/4/29 15:32 @introduction in、not in """ s = {10, 20, 30, 40, 50} print(10 in s)# True print(100 in s)# False print(15 not in s)# True

3.4 添加2种方式 1. add(Object obj):set集合添加指定元素。
2. extend(Iterator iter):遍历序列(列表、元组、集合等),获取其中的元素并添加到set集合。
3.4.1 add()-添加指定元素
""" @author GroupiesM @date 2022/6/28 11:06 @introduction add(Object obj):添加一个元素 """ s = {10, 20, 30, 40, 50}s.add(60) print(s)# {40, 10, 50, 20, 60, 30}

3.4.1 update()-遍历iterable将元素添加到set
""" @author GroupiesM @date 2022/6/28 11:06 @introduction update(Iterator iter):添加一个迭代器(列表、元组、集合等) """ s = {10, 20, 30, 40, 50}s.update(['a', 'b', 'c']) print(s)# {'a', 40, 10, 50, 20, 'c', 'b', 60, 30}

3.5 删除4种方式 1. remove(Object obj):删除指定Key的元素。
??1)一次删除一个元素。
??2)Key不存在则抛出KeyError。
2. discard(Integer i):删除指定Key的元素。
??1)Key不存在不报错。
3. pop( ):删除最左边的一个元素。(左侧弹出)
4. clear():清空集合。
3.5.1 remove()-删除指定Key
""" @author GroupiesM @date 2022/6/22 17:14 @introduction remove(Object obj):删除指定元素,不存在抛出KeyError """ s = {10, 20, 30, 40, 50} s.remove(10) print(s)# {40, 50, 20, 30}

3.5.2 discard()-删除指定Key(不存在不报错)
""" @author GroupiesM @date 2022/6/22 17:15 @introduction discard(Object obj):删除指定元素,不存在不报错 """ s = {10, 20, 30, 40, 50} s.discard(15) s.discard(20) print(s)# {40, 10, 50, 30}

3.5.3 pop()-左侧弹出1个
""" @author GroupiesM @date 2022/6/22 17:15 @introduction pop():删除一个任意元素(左侧弹出) """ s = {10, 20, 30, 40, 50} s.pop() print(s)# {10, 50, 20, 30}

3.5.4 clear()-清空列表
""" @author GroupiesM @date 2022/6/22 17:15 @introduction clear():清空 """ s = {10, 20, 30, 40, 50} s.clear() print(s)# set()

3.6 判断-集合关系4种方式
""" @author GroupiesM @date 2022/4/29 15:43 @introduction 集合关系概念: 1.子集:如果a集合是b集合的子集,那么a集合中的所有元素,在b集合中都存在,那么a就是b的子集,记作"a∈b" 2.真子集:在上述情况下,b中至少有一个元素不属于a,那么a就是b的真子集,记作"A?B" 3.超集:如果a是b的真子集,那么b就是a的超集 判断集合关系4种方式: 1. 元素是否相等 == 或 != 2. 是否子集 issubset() 3. 是否超集 (这里超集定义与数学中不同,ab集合元素完全相等时,也互为超集) issuperset() 4. 是否无交集 isdisjoint() """

3.6.1 判断集合关系-==或!=
""" @author GroupiesM @date 2022/6/22 17:19 @introduction 1. 元素是否相等 == 或 != """ a = {1, 2} a1 = {1, 2} b = {1, 2, 3, 4, 5} c = {5, 6} d = {6, 7}print('----------元素是否相等----------') print(a == a1)# True print(a != a1)# Fasle

3.6.2 判断集合关系-issubset()
""" @author GroupiesM @date 2022/6/22 17:20 @introduction 2. 是否子集 issubset() """ a = {1, 2} a1 = {1, 2} b = {1, 2, 3, 4, 5} c = {5, 6} d = {6, 7}print('----------是否子集 issubset()----------') print(a.issubset(a1))# True print(a.issubset(b))# True print(a.issubset(c))# False

3.6.3 判断集合关系-issuperset()
""" @author GroupiesM @date 2022/6/22 17:20 @introduction 3. 是否超集 (这里超集定义与数学中不同,ab集合元素完全相等时,也互为超集) issuperset() """ a = {1, 2} a1 = {1, 2} b = {1, 2, 3, 4, 5} c = {5, 6} d = {6, 7}print('----------是否超集 issuperset()----------') print(a.issuperset(a1)) # True print(b.issuperset(a)) # True print(b.issuperset(c)) # False

3.6.4 判断集合关系-isdisjoint()
""" @author GroupiesM @date 2022/6/22 17:20 @introduction 4. 是否无交集 isdisjoint() """ a = {1, 2} a1 = {1, 2} b = {1, 2, 3, 4, 5} c = {5, 6} d = {6, 7}print('----------是否无交集 isdisjoint()----------') print(a.isdisjoint(a1)) # False print(b.isdisjoint(c)) # False print(b.isdisjoint(d)) # True

3.7 数学计算-集合
""" @author GroupiesM @date 2022/4/29 15:59 @introduction 交集: {1,2} & {2,3} => {2} 方式一:intersection() 方式二:& 并集: {1,2} & {2,3} => {1,2,3} 方式一:union() 方式二:| 差集: {1,2} x {2,3} => {1} 方式一:difference() 方式二:- 对称差集: {1,2} & {2,3} => {1,3} 方式一:symmetric_difference() 方式二:^=> shift + 数字6 """ s1 = {1, 2} s2 = {2, 3} print('---------交集 {2} --------') print(s1.intersection(s2)) print(s1 & s2)print('---------并集 {1, 2, 3}--------') print(s1.union(s2)) print(s1 | s2)print('---------差集 {1}--------') print(s1.difference(s2)) print(s1 - s2)print('---------对称差集 {1,3}--------') print(s1.symmetric_difference(s2)) print(s1 ^ s2)

3.8 集合生成式
""" @author GroupiesM @date 2022/4/29 16:06 @introduction 全称"生成集合的公式" 语法格式: {fx(i) for i in range(n,m)} fx(i): 表达式 i : 自定义变量 range(n,m) : 可迭代对象 注意事项: 将{}改为[],就是list 列表生成式 """ set1 = {i * 2 for i in range(1, 5)} print(set1)# {8, 2, 4, 6}

四、字典dict -> {k1:v1,…} 4.1 简介
""" @author GroupiesM @date 2022/4/28 16:09 @introduction 列表:list = ['hello', 'world', 100] 字典:dict = {'name': '张三', 'age': 100} 元组:tuple = ('python','hello',90) 集合: set= {'python', 'hello', 90} 字符串: str = 'python'字典:python内置的数据结构之一,与列表一样是一个可变序列 以【键值对】方式存储数据,字典是一个无序数列 m1 = {'name': '张三', 'age': 100}实现原理:字典的实现原理与查字典类似,查字典实现根据部首或拼音查找相应的页码 Python中的字典是根据key查找value所在的位置 id = hash(key) 字典视图:详见 4.8 获取字典视图种方式 dict_keys: dict_values: dict_items: """ dict = {'name': '张三', 'age': 100} print(type(dict))# print(dict)# {'name': '张三', 'age': 100}

4.2 创建
""" @author GroupiesM @date 2022/4/28 16:17 @introduction 字典创建方式: 方式一:使用花括号 {},元素之间英文逗号分隔 scores = {'name': '张三', 'age': 100} 方式二:内置函数 dict() 类型转换 dict(k1=v1,k2=v2,...) """ '''方式一''' dct1 = {'name': '张三', 'age': 100, 'salary': 1888} print(dct1)# {'name': '张三', 'age': 100, 'salary': 1888}'''方式二''' dct2 = dict(name='张三', age=100, salary=1888) print(dct2)# {'name': '张三', 'age': 100, 'salary': 1888}'''空字典''' dct3 = {}# 空字典 print(dct3)# {}

4.3 特点
""" @author GroupiesM @date 2022/4/28 16:52 @introduction 1) 所有元素都是 k-v键值对,key不允许重复,value可以重复 2) 字典中的元素是无序的 3) 字典中的key必须是基本类型(不可变对象) 4) 字典也可以根据需要动态的伸缩 5) 字典会浪费比较大的内存,是一种使用空间换时间的数据结构 """ ''' 1) 所有元素都是 k-v键值对,key不允许重复,value可以重复 {'name': '李四'} {'name': '张三', 'nickname': '张三'} ''' m1 = {'name':'张三','name':'李四'} print(m1)m1 = {'name':'张三','nickname':'张三'} print(m1)

4.4 查找 k->v
""" @author GroupiesM @date 2022/4/28 16:26 @introduction m1 = {'name': '张三', 'age': 100, 'salary': 1888} 方式一: []: 举例m1['张三'] 方式二: get(): 举例 m1.get('张三') 区别: []:如果不存在指定key,抛出keyError异常 get():如果不存在指定key,返回None,可以通过参数设置默认value,查不到key时返回默认值 """ m1 = {'name': '张三', 'age': 100, 'salary': 1888}'''方式一:[]获取name''' name = m1['name'] print(name)# 张三'''方式二:get()获取age''' age = m1.get('age') print(age) # 100'''方式二:get()获取不存在的key''' address = m1.get('address') print(address) # None'''方式二:get()获取不存在的key,并指定默认值''' address = m1.get('address','china') print(address) # china'''方式二:get()获取存在的key,并指定默认值,默认值不生效''' salary = m1.get('salary','1万') print(salary) # 1888

4.5 判断 in¬ in
""" @author GroupiesM @date 2022/4/28 16:34 @introduction key的判断 in: 指定key在字典中存在返回True not in:指定key在字典中不存在返回True """ m1 = {'name': '张三', 'age': 100, 'salary': 1888} b1 = 'name' in m1 b2 = 'address' in m1 b3 = 'country' not in m1 print(b1) # True print(b2) # False print(b3) # True

4.6 添加元素-k=v
""" @author GroupiesM @date 2022/4/28 16:37 @introduction dict['key']= xxx """ m1 = {'name': '张三', 'age': 100, 'salary': 1888} m1['country'] = '中国' print(m1)# {'name': '张三', 'age': 100, 'salary': 1888, 'country': '中国'}

4.7 删除元素-del
""" @author GroupiesM @date 2022/4/28 16:37 @introduction del dict['key'] """ m1 = {'name': '张三', 'age': 100, 'salary': 1888} del m1['salary'] print(m1) # {'name': '张三', 'age': 100}

4.8 获取字典视图3种方式
""" @author GroupiesM @date 2022/4/28 16:40 @introduction 方式1:keys() : 获取字典中所有key返回值类型: 方式2:values() : 获取字典中所有value返回值类型: 方式3:items() : 获取字典中所有key,value对返回值类型: """

4.8.1 获取字段中所有key-keys()
""" @author GroupiesM @date 2022/6/22 14:51 @introduction """ map = {'name': '张三', 'age': 100, 'salary': 1888} key_lst = map.keys() print(key_lst, type(key_lst))# dict_keys(['name', 'age', 'salary']) ''' dict_keys -> list 其中dict_keys是元组类型(), 详见b1元组tuple ''' print(list(key_lst))# ['name', 'age', 'salary']

4.8.2 获取字典中所有value-values()
""" @author GroupiesM @date 2022/6/22 14:51 @introduction """ map = {'name': '张三', 'age': 100, 'salary': 1888} value_lst = map.values() print(value_lst, type(value_lst))# dict_values(['张三', 100, 1888]) ''' dict_keys -> list 其中dict_keys是元组类型(), 详见b1元组tuple ''' print(list(value_lst))# ['张三', 100, 1888]

4.8.3 获取字典中所有kv对-items()
""" @author GroupiesM @date 2022/6/22 14:52 @introduction """ map = {'name': '张三', 'age': 100, 'salary': 1888} item_lst = map.items() print(item_lst, type(item_lst))# dict_items([('name', '张三'), ('age', 100), ('salary', 1888)]) ''' dict_keys -> list 其中dict_keys是元组类型(), 详见b1元组tuple ''' print(list(item_lst))# [('name', '张三'), ('age', 100), ('salary', 1888)]

4.9 遍历
""" @author GroupiesM @date 2022/4/28 16:49 @introduction i是dict的所有key 通过dict.get(i)、或dict[i]获取每个key对应的value for i in dict: print(i,dict.get(i)) for i in dict: print(i,dict[i]) """ ''' 遍历key-value name 张三 age 100 salary 1888 ''' m1 = {'name': '张三', 'age': 100, 'salary': 1888} for k in m1: print(k, m1.get(k))''' 遍历value 张三 100 1888 ''' for v in m1.values(): print(v,end="\t")

4.10 转换-zip->dict
""" @author GroupiesM @date 2022/6/22 15:22 @introduction 语法格式: {k: v for k, v in zip} k : 自定义变量key v : 自定义变量value zip : 可迭代zip对象 内置函数zip(): 用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回有这些元组组成的列表 key-value数量不一致时,参考短板效应""" items = ['水果', '书本', '鱼缸', '马桶'] prices = [10, 20, 30]'''方式一:dict()''' zip1 = zip(items, prices) dct1 = dict(zip1) print(type(zip1), zip1)# print(type(dct1), dct1)# {'水果': 10, '书本': 20, '鱼缸': 30}'''方式二:{k: v for k, v in zip}''' zip2 = zip(items, prices) dct2 = {k: v for k, v in zip2}# zip1只能使用一次,如果此处继续使用zip1,则返回空字典dct2 print(type(dct2), dct2)# {'水果': 10, '书本': 20, '鱼缸': 30}

22/06/28

M

    推荐阅读