python: set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

>>> x = set("jihite")

>>> y = set(['d', 'i', 'm', 'i', 't', 'e'])

>>> x #把字符串转化为set,去重了

set(['i', 'h', 'j', 'e', 't'])

>>> y

set(['i', 'e', 'm', 'd', 't'])

>>> x & y #交

set(['i', 'e', 't'])

>>> x | y #并

set(['e', 'd', 'i', 'h', 'j', 'm', 't'])

>>> x - y #差

set(['h', 'j'])

>>> y - x

set(['m', 'd'])

>>> x ^ y #对称差:x和y的交集减去并集

set(['d', 'h', 'j', 'm'])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

>>> x

set(['i', 'h', 'j', 'e', 't'])

>>> s = set("hi")

>>> s

set(['i', 'h'])

>>> len(x) #长度

>>> 'i' in x

True

>>> s.issubset(x) #s是否为x的子集

True

>>> y

set(['i', 'e', 'm', 'd', 't'])

>>> x.union(y) #交

set(['e', 'd', 'i', 'h', 'j', 'm', 't'])

>>> x.intersection(y) #并

set(['i', 'e', 't'])

>>> x.difference(y) #差

set(['h', 'j'])

>>> x.symmetric_difference(y) #对称差

set(['d', 'h', 'j', 'm'])

>>> s.update(x) #更新s,加上x中的元素

>>> s

set(['e', 't', 'i', 'h', 'j'])

>>> s.add(1) #增加元素

>>> s

set([1, 'e', 't', 'i', 'h', 'j'])

>>> s.remove(1) #删除已有元素,如果没有会返回异常

>>> s

set(['e', 't', 'i', 'h', 'j'])

>>> s.remove(2)




Traceback (most recent call last):

File "<pyshell#29>", line 1, in <module>

s.remove(2)

KeyError: 2

>>> s.discard(2) #如果存在元素,就删除;没有不报异常

>>> s

set(['e', 't', 'i', 'h', 'j'])

>>> s.clear() #清除set

>>> s

set([])

>>> x

set(['i', 'h', 'j', 'e', 't'])

>>> x.pop() #随机删除一元素

'i'

>>> x

set(['h', 'j', 'e', 't'])

>>> x.pop()

'h'