No6.集合的魔法

1.集合由不同元素组成

2.集合是无序的

3.集合中元素必须是不可变类型

1 >>> s = {1, 2, 3}
2 >>> s1 = set("Hello")
3 >>> print(s, s1)
4 {1, 2, 3} {'e', 'o', 'H', 'l'}
5 #s1充分的体现了集合的无序性
集合的构建
1 >>> s = {1, 2, 3, 4, 5, 6}
2 >>> s.add("s")
3 >>> s
4 {1, 2, 3, 4, 5, 6, 's'}
5 >>> s.add(3)  #充分体现了集合中元素不可重复的性质
6 >>> s
7 {1, 2, 3, 4, 5, 6, 's'}
集合元素的添加
1 >>> s = {1, 2, 3}
2 >>> s1 = s.copy()
3 >>> s1
4 {1, 2, 3}
集合的拷贝
 1 >>> s = {1, 2, 3, 4, 5, 6}
 2 #随机删除,并返回删除的元素
 3 >>> s.pop()
 4 1
 5 >>> s
 6 {2, 3, 4, 5, 6}
 7 
 8 #指定元素删除,若元素不存在会报错
 9 >>> s.remove(1)
10 Traceback (most recent call last):
11   File "<pyshell#6>", line 1, in <module>
12     s.remove(1)
13 KeyError: 1
14 >>> s.remove(2)
15 >>> s
16 {3, 4, 5, 6}
17 
18 #指定元素删除,不存在不会报错
19 >>> s.discard(1)
20 >>> s.discard(3)
21 >>> s
22 {4, 5, 6}
集合元素的删除
 1 >>> p_1 = {'shi', 'fdfd', 'trony'}
 2 >>> l_1 = {'shi', 'fdfd', '123'}
 3 >>> print(p_1, l_1)
 4 {'shi', 'fdfd', 'trony'} {'123', 'shi', 'fdfd'}
 5 
 6 #交集
 7 >>> print(p_1.intersection(l_1))
 8 {'shi', 'fdfd'}
 9 >>> print(p_1&l_1)
10 {'shi', 'fdfd'}
11 
12 #求并集
13 >>> print(p_1.union(l_1))
14 {'123', 'trony', 'shi', 'fdfd'}
15 >>> print(p_1 | l_1)
16 {'123', 'trony', 'shi', 'fdfd'}
17 
18 #求差集
19 >>> print(l_1 - p_1)
20 {'123'}
21 >>> print(l_1.difference(p_1))
22 {'123'}
23 >>> print(p_1 - l_1)
24 {'trony'}
25 >>> print(p_1.difference(l_1))
26 {'trony'}
集合的运算
1 >>> s1 = frozenset("hello")
2 >>> print(s1)
3 frozenset({'l', 'o', 'e', 'h'})
不可变集合

猜你喜欢

转载自www.cnblogs.com/Tronyshi/p/9249339.html