python基础数据类型(四)集合
1.集合dict
集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:
去重,把一个列表变成集合,就自动去重了。
关系测试,测试两组数据之前的交集、差集、并集等关系。
2.创建
# #创建 # #one set1 = set({1,2,3,'哈哈','呵呵'}) print(set1) # #two set2 = {1,2,3,'哈哈','呵呵'} print(set2)
3.增加
#增 #one add set1 = set({1,2,3,'哈哈','呵呵'}) set1.add('嘿嘿') print(set1) #two update set1 = set({1,2,3,'哈哈','呵呵'}) set1.update('今天是个好日子') print(set1)
4.删除
#删除 set1 = set({1,2,3,'哈哈','呵呵'}) #pop set1.pop() #随机删除一个元素 print(set1) #remove set1 = set({1,2,3,'哈哈','呵呵'}) set1.remove(1) #按元素删除 print(set1) #clear set1 = set({1,2,3,'哈哈','呵呵'}) set1.clear() #清空 print(set1) #del set1 = set({1,2,3,'哈哈','呵呵'}) del set1
5.查看
#查 set1 = set({1,2,3,'哈哈','呵呵'}) for i in set1: print(i)
6.交集 & 或者 intersection
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 & set2) print(set1.intersection(set2))
7.并集 | 或者 union
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7} print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7}
8.差集 - 或者 difference
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 - set2) print(set1.difference(set2))
9.反交集 ^ 或者 symmetric_difference
set1 = {1,2,3,4,5} set2 = {4,5,6,7,8} print(set1 ^ set2) print(set1.symmetric_difference(set2))
10.子集与超集
set1 = {1,2,3} set2 = {1,2,3,4,5,6} print(set1 < set2) print(set1.issubset(set2)) print(set2 > set1) print(set2.issuperset(set1))