十、集合
python集合其实跟我们高一数学学的集合没啥两样,大括号表示,具有无序性。
- 创建集合
>>> s = {}
>>> type(s)
<class 'dict'>
>>> set1 = {1,2,4,3,4,5,2}
>>> type(set1)
<class 'set'>
>>> set1
{1, 2, 3, 4, 5}
>>> set2 = set(['a', 'b', 'c'])
>>> set2
{'b', 'c', 'a'}
- 访问集合
集合具有无序性,因此不能通过索引访问,但是可以迭代。
>>> set1
{1, 2, 3, 4, 5}
>>> for i in set1:
print(i)
1
2
3
4
5
也可以应用成员操作符
>>> 1 in set1
True
>>> 6 in set1
False
>>> 2 not in set1
False
- 可变集合
add()方法添加元素, remove()方法移除元素。
>>> set1
{1, 2, 3, 4, 5}
>>> set1.add(6)
>>> set1
{1, 2, 3, 4, 5, 6}
>>> set1.remove(1)
>>> set1
{2, 3, 4, 5, 6}
- 不可变集合
用frozenset()函数将一个可变集合“冰冻”成不可变集合。
>>> set1
{2, 3, 4, 5, 6}
>>> set1 = frozenset(set1)
>>> set1.add(1)
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
set1.add(1)
AttributeError: 'frozenset' object has no attribute 'add'
- 集合的应用
集合可以很方便的删除重复元素。(之前在学习成员操作符的时候也说过可以借助成员操作符通过迭代的方式去除重复数据)
>>> list1= [1, 2, 3, 5, 3, 4, 8, 0]
>>> list2 = list(set(list1))
>>> list2 # 不过由于集合具有无序性,因此新生成的列表的元素顺序可能会改变,这点需要注意下。
[0, 1, 2, 3, 4, 5, 8]
- 集合内置方法
__and__ __class__ __contains__ __delattr__ __dir__ __doc__ __eq__ __format__
__ge__ __getattribute__ __gt__ __hash__ __iand__ __init__ __init_subclass__
__ior__ __isub__ __iter__ __ixor__ __le__ __len__ __lt__ __ne__ __new__
__or__ __rand__ __reduce__ __reduce_ex__ __repr__ __ror__ __rsub__ __rxor__
__setattr__ __sizeof__ __str__ __sub__ __subclasshook__ __xor__
add clear copy difference difference_update discard intersection intersection_update
isdisjoint issubset issuperset pop remove symmetric_difference symmetric_difference_update
union update

浙公网安备 33010602011771号