1.集合
Python中的集合与数学上的集合是一致的,不允许有重复元素,而且可以进行交集、并集、差集等运算。
2.创建集合
#字面量方式
set1 = {1, 2, 3, 3, 3, 2}
print(set1) # {1, 2, 3}
print('length = ', len(set1)) # length = 3
#构造器语法
set2 = set(range(1, 10))
set3 = set((1, 2, 3, 3, 2, 1))
print(set2, set3) # {1, 2, 3, 4, 5, 6, 7, 8, 9} {1, 2, 3}
#推导式语法
set4 = {num for num in range(1, 100) if num % 3 == 0 or num % 5 == 0} # {3, 5, 6, 9, 10, 12, 15, 18...
print(set4)
3.集合添加和删除元素
set1.add(4) # 添加
set1.add(5)
print(set1) # {1, 2, 3, 4, 5}
set2.update([11, 12])
print(set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12}
set2.discard(5) # 移除5
print(set2) # {1, 2, 3, 4, 6, 7, 8, 9, 11, 12}
if 4 in set2:
set2.remove(4) # 移除4
print(set2) # {1, 2, 3, 6, 7, 8, 9, 11, 12}
print(set3.pop()) # 1
print(set3) # {2, 3}
4.集合运算
print(set1 & set2) # {1, 2, 3} 交集
print(set1.intersection(set2))
print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12} 并集
print(set1.union(set2))
print(set1 - set2) # {4, 5} 差集
print(set1.difference(set2))
print(set1 ^ set2) # {4, 5, 6, 7, 8, 9, 11, 12}
print(set1.symmetric_difference(set2))
5.判断子集和超集
print(set2 <= set1) # False
print(set2.issubset(set1))
print(set3 <= set1) # True
print(set3.issubset(set1))
print(set1 >= set2) # False
print(set1.issuperset(set2))
print(set1 >= set3) # True
print(set1.issuperset(set3))
标签:11,12,Python,print,set1,set2,set3,集合,数据结构 From: https://www.cnblogs.com/zhishu/p/17216061.html