集合元素的唯一性:
>>> s={1,2,3,4,5}
>>> s.add(3)
>>> s
{1, 2, 3, 4, 5}
>>> s.add(6)
>>> s
{1, 2, 3, 4, 5, 6}
将列表转化为集合:
>>> t=[1,2,3]
>>> s=set(t)
>>> s
{1, 2, 3}
创建空集合:
>>> t=[1,2,3]
>>> s=set(t)
>>> s
{1, 2, 3}
在集合中增减元素:
>>> s={1,2,3,4,5}
>>> s.add(6)
>>> s
{1, 2, 3, 4, 5, 6}
>>> s.remove(3)
>>> s
{1, 2, 4, 5, 6}
可以用min(),max(),len(),sum()对集合进行操作
集合是无序的,所以无法通过下标对集合进行索引:
>>> s[0]
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
s[0]
TypeError: 'set' object is not subscriptable
用for循环遍历集合:
>>> for i in s:
print(i)
1
2
3
4
5
6
判断元素是否在集合中:
s={1, 2, 3, 4, 5, 6}
>>> 3 in s
True
>>> 3 not in s
False
>>> 8 in s
False
>>> 8 not in s
True
>>> {1,2,3} in s
False
>>> 1 in s and 2 in s and 3 in s
True
>>> {1,2,3,4,5,6}==s
True
>>> {1,2,3}<s
True
< 等价于⊂\subset⊂
> 等价与⊃\supset⊃
<= 等价于⊆\subseteq⊆
>= 等价于⊇\supseteq⊇
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1|s2
{1, 2, 3, 4, 5, 6, 7, 8}
>>> s1&s2
{4, 5}
>>> s1^s2
{1, 2, 3, 6, 7, 8}
| 等价于 ∪\cup∪
& 等价于 ∩\cap∩
^等价于Δ\DeltaΔ :对称差
>>> s1-s2
{1, 2, 3}
>>> s2-s1
{8, 6, 7}