文章目录
概念
作用:去重,关系运算,
可变类型和不可变类型的定义:
可变类型是不可hash类型 不可变类型是可hash类型
集合定义:
集合:可以包含多个元素,用逗号分割, 集合的元素遵循三个原则:
1.每个元素必须是不可变类型(可hash,可作为字典的key)
2.没有重复的元素
3.无序
注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
主要方法:
1、长度len
pythons={'asdf','bargn','cceao','deryi','eagtbasefv','fargaeg'}
len(pythons)
6
2、成员运算in和not in
'asdf' in pythons
True
3、"|" 合集
pythons2={'asdf','cceao','deryi','eagtbasefv','fargaeg','adsfager'}
pythons | pythons2
{‘adsfager’, ‘asdf’, ‘bargn’, ‘cceao’, ‘deryi’, ‘eagtbasefv’, ‘fargaeg’}
4、&交集
pythons & pythons2
{‘asdf’, ‘cceao’, ‘deryi’, ‘eagtbasefv’, ‘fargaeg’}
5、"-"差集
print(pythons - pythons2)
print(pythons2 - pythons)
{‘bargn’}
{‘adsfager’}
6、 "^"对称差集
pythons ^ pythons2
{‘adsfager’, ‘bargn’}
7、==
pythons == pythons2
False
8、父集:>,>=
pythons3 = {'asdf', 'cceao', 'deryi', 'eagtbasefv', 'fargaeg'}
print(pythons3 > pythons)
print(pythons3 >= pythons)
False
False
9、子集:<,<=
print(pythons3 < pythons)
print(pythons3 <= pythons)
True
True
其它方法
set的方法和object的方法
a = set.__dict__.keys()
b = object.__dict__.keys()
print(a,'\n',b)
dict_keys(['__repr__', '__hash__', '__getattribute__', '__lt__', '__le__',
'__eq__', '__ne__', '__gt__', '__ge__', '__iter__', '__init__', '__sub__',
'__rsub__', '__and__', '__rand__', '__xor__', '__rxor__', '__or__', '__ror__',
'__isub__', '__iand__', '__ixor__', '__ior__', '__len__', '__contains__', '__new__',
'add', 'clear', 'copy', 'discard', 'difference', 'difference_update', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', '__reduce__',
'remove', '__sizeof__', 'symmetric_difference', 'symmetric_difference_update',
'union', 'update', '__doc__'])
dict_keys(['__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__',
'__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__init__',
'__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__',
'__format__', '__sizeof__', '__dir__', '__class__', '__doc__'])
set的独有方法()
print(a - b)
{'__xor__', '__iter__', '__ror__', '__or__',
'symmetric_difference_update', '__rsub__', 'clear',
'__rxor__', '__iand__', '__ixor__',
'difference_update', 'issubset', 'union', 'add',
'__isub__', '__sub__', '__ior__', '__rand__',
'update', 'isdisjoint', 'issuperset', '__len__', 'copy',
'intersection', 'difference', 'intersection_update',
'__and__', 'symmetric_difference', 'discard',
'__contains__', 'remove', 'pop'}