定义
1.由不同元素组成
2.无序排列的的可hash值,可以作为字典的key
3.不可变类型
定义集合示例
a = {1,1,2,2,3,4,5,6,7,8,9}print(a)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
或
a = set('123456789')print(a)
{'3', '4', '7', '5', '6', '8', '9', '1', '2'}
转换为集合
li = [1,2,3,4,5,6]v = set(li)print(v)
{1, 2, 3, 4, 5, 6}
不可变集合
a = frozenset('1''2''3')print(a)
frozenset({'3', '1', '2'})
可变集合方法
添加更新拷贝
add()
添加集合元素,一次只能更新一个值
a = {1,2,3}a.add(4)print(a)
{1, 2, 3, 4}
update()
集合更新,一次可以更新多个值
a = {1,2,3}b = {4,5,6}v = a.update(b)print(v)print(a)
None{1, 2, 3, 4, 5, 6}
copy()
集合复制
a = {1,2,3}v = a.copy()print(a)print(v)
{1, 2, 3}{1, 2, 3}
删除/移除/清除
clear()
清除集合内容
a = {1,2,3}a.clear()print(a)
set()
pop()
随机删除一个元素
a = set("1""2""3""4""5")a.pop()print(a)
{'1', '4', '5', '2'}
remove()
指定元素移除,不存在报错
a = set("1""2""3""4""5")a.remove('4')print(a)
{'1', '3', '5', '2'}
discard()
指定元素移除,不存在返回原集合
a = set("1""2""3""4""5")a.discard('8')print(a)
{'3', '2', '4', '1', '5'}
集合关系运算
intersection()
交集
intersection()方法可以用"&"或"and"符号代表,如:print(a&b)
a = set('1''2''3''4''5''6''7''8''9')b = set('1''3''5''7''9')v = a.intersection(b)# v = a & b# v = a and bprint(v)
{'3', '5', '1', '9', '7'}
union()
并集
union()方法可以用"|"或"or"符号代表,如:print(a|b)
a = set('1''2''3''4''5''6''7''8''9')b = set('1''3''5''7''9')v = a.union(b)# v = a | b# v = a or bprint(v)
{'7', '1', '2', '3', '5', '8', '4', '9', '6'}
difference()
差集
difference()方法可以用"-"符号代表,如:print(a-b)
a = set('1''2''3''4''5''6''7''8''9')b = set('1''3''5''7''9')v = a.difference(b)# v = a - bprint(v)
{'4', '8', '6', '2'}
symmetric_difference()
交叉补集,将两个集合不重合部分进行并集
symmetric_difference()方法可以用"^"符号代表,如:print(a^b)
a = set('2''3''4''5''6''7''8')b = set('1''3''5''7''9')v = a.symmetric_difference(b)# v = a ^ bprint(v)
{'2', '6', '4', '1', '9', '8'}
intersection_update()
注:集合关系运算后跟_update说明直接赋值给首选集
a = set('1''2''3''4''5')b = set('3''4''5''6''7')v = a.intersection_update(b)print(v)print(a)
None{'5', '3', '4'}
issuperset()
超集(父集)判断
issuperset()方法可以用">"来表示和判断
a = set('1''2''3''4''5''6''7''8''9')b = set('1''3''5''7''9')v = a.issuperset(b)# v = a > bprint(v)
True
issubset()
子集判断
issubset()方法可以用"<"来表示和判断
a = set('1''2''3''4''5''6''7''8''9')b = set('1''3''5''7''9')v = a.issubset(b)# z = a < bprint(v)
False