元组:如果元祖里面只有一个元素且不加逗号,那此元素是什么类型,就是什么类型
tu1 = (1) tu2 = (1,) print(tu1,type(tu1)) # 1 <class 'int'> print(tu2,type(tu2)) #(1,) <class 'tuple'> tu1 = ([1]) tu2 = ([1],) print(tu1,type(tu1)) #[1] <class 'list'> print(tu2,type(tu2)) #([1],) <class 'tuple'>
集合
集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。
集合最重要的两点:
去重,把一个列表变成集合,就自动去重了;
关系测试,测试两组数据之前的交集、差集、并集等关系。
①创建集合
set1 = set({123,"ppd"}) set2 = {123,"ppd"} print(set1,set2) #{123, 'ppd'} {123, 'ppd'}
②集合的增
set1 = {123,"ppd"} set1.add("苹果") print(set1) {'苹果', 123, 'ppd'} #update:迭代着增加 set1 = {123, "ppd"} set1.update("ppd") print(set1) #{'ppd', 123, 'p', 'd'} set1.update("苹果") print(set1) {'ppd', 'p', 'd', '苹', 123, '果'} set1.update([1, 2, 3]) print(set1) {1, 2, 3, 'ppd', 'p', 'd', '苹', 123, '果'}
③集合的删
set1 = {123, "ppd", "苹果"} set1.remove(123) # 删除一个元素 print(set1) set1.pop() # 随机删除一个元素 print(set1) set1.clear() # 清空集合 print(set1) #set() del set1 # 删除集合 print(set1) #NameError: name 'set1' is not defined
④集合的查
set1 = {123, "ppd", "苹果"} for i in set1: print(i)
⑤集合的其他运用
交集:&或者intersection
set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 & set2) # {4, 5} print(set1.intersection(set2)) # {4, 5}
反交集:^ 或者symmetric_difference
set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 ^ set2) # {1, 2, 3, 6, 7, 8} print(set1.symmetric_difference(set2)) #{1, 2, 3, 6, 7, 8}
并集:| 或者 union
set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8} print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8}
差集:- 或者 difference
set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} print(set1 - set2) # {1, 2, 3} 输出set1(set2中有set1的那部分不输出) print(set1.difference(set2)) #{1, 2, 3}
子集与超集
set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5, 6} print(set1 < set2) #set1是set2子集 print(set1.issubset(set2)) # set1是set2子集 print(set2 > set1) #set2是set1超集 print(set2.issuperset(set1)) # set2是set1超集
frozenset不可变集合,让集合变成不可变类型
s = frozenset("meppd") print(s, type(s)) #frozenset({'p', 'd', 'e', 'm'}) <class 'frozenset'>