python基本数据类型——集合
集合
无序可变序列,集合中元素不允许重复,即每个元素都是唯一的
集合中的元素按照升序排列
1 # 创建集合
2 >>aset = set([0,2,4,5,7,2,3,5,9,0])
3 >>print(aset)
4 {0, 2, 3, 4, 5, 7, 9}
5 # 添加元素,按顺序插入集合
6 >>aset.add(6)
7 >>print(aset)
8 {0, 2, 3, 4, 5, 6, 7, 9}
9
10 #删除元素
11 >>aset.pop()
12 >>print(aset)
13 {2, 3, 4, 5, 6, 7, 9}
14 # remove删除指定元素
15 >>aset.remove(2)
16 {3, 4, 5, 6, 7, 9}
17 # clear 清空
18 >>aset.clear()
19 >>print(aset)
20 set()
集合操作
1 >>aset = {1,2,3,5,7}
2 >>bset = {4,5,6,7}
3 #并集
4 >>aset | bset
5 {1, 2, 3, 4, 5, 6, 7}
6 # 交集
7 >>aset & bset
8 {5, 7}
9 >>aset.intersection(bset)
10 {5, 7}
11 # 差集
12 >>aset.difference(bset)
13 {1, 2, 3}
14 # 对称差
15 >>aset.symmetric_difference(bset)
16 {1, 2, 3, 4, 6}
17 # 测试是否为子集
18 >>x={1,2}
19 >>x.issubset(aset)
20 True
21 >>x.issubset(bset)
22 False
由于集合中元素是唯一的,可以使用集合提取序列中单一元素,或生成不重复的随机序列
1 >>from random import randint
2 >>from collections import Counter
3 >>listR = [randint(0,100) for i in range(40)]
4 >>numFreq = Counter(listR)
5 >>print(numFreq)
6 Counter({3: 1,
7 4: 2,
8 7: 1,
9 13: 1,
10 17: 1,
11 19: 1,
12 23: 1,
13 26: 1,
14 44: 1,
15 50: 1,
16 52: 1,
17 53: 1,
18 54: 1,
19 55: 1,
20 60: 1,
21 62: 1,
22 68: 1,
23 73: 1,
24 77: 1})
25 # 随机数中包含2个4
26 >>noRepeat = set(listR)
27 >>print(noRepeat)
28 3, 4, 7, 13, 17, 19, 23, 26, 44, 50, 52,
53, 54, 55, 60, 62, 68, 73, 77}
29 # 生成的集合中只有一个4