标签:图片 自动 style inter 需要 div splay 删除 不能
1.集合
1 ‘‘‘
2 集合:可变数据类型,里面存的元素必须是不可变数据类型。
3 集合无序,里面的元素不能重复。将列表转换为集合在转换为集合就将有重复元素的list去重了。
4 集合{}
5 ‘‘‘
6
7 # 创建一个集合
8 set1 = set({1, 2, 3})
9 print(set1) # {1, 2, 3}
10
11 # 第二种创建一个集合的方法
12 set2 = {1, 2, 3}
13
14 print(set2, type(set2)) # {1, 2, 3}
15
16 # set2 = {1, 2, 3, [4, 5], {‘name‘ : ‘alex‘}} # 报错
17
18 # print(set2)
19
20
21 # 增
22
23 set1 = {‘alex‘, ‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘}
24
25 # 增,使用add
26 set1.add(‘python‘)
27 print(set1) # {‘ritian‘, ‘python‘, ‘wusir‘, ‘egon‘, ‘alex‘, ‘barry‘}
28
29 # 不能有重复元素
30 set1 = {‘alex‘, ‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘, ‘alex‘}
31 print(set1) # {‘wusir‘, ‘barry‘, ‘egon‘, ‘ritian‘, ‘alex‘} 自动去重
32
33
34 # 增 update,迭代的增加
35
36 set1.update(‘abc‘)
37
38 print(set1) # {‘egon‘, ‘b‘, ‘barry‘, ‘a‘, ‘wusir‘, ‘c‘, ‘ritian‘, ‘alex‘}
39
40
41
42 set1 = {‘alex‘, ‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘, ‘alex‘}
43
44 # 删
45
46 # 删 随机删除,返回值就是删除的那一个
47 print(set1.pop()) # alex
48
49 print(set1) # {‘alex‘, ‘egon‘, ‘ritian‘, ‘barry‘}
50
51
52 set1 = {‘alex‘, ‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘, ‘alex‘}
53 # 删,按元素删除, 没有要删的元素会报错
54
55 set1.remove(‘alex‘)
56
57 print(set1) # {‘wusir‘, ‘egon‘, ‘ritian‘, ‘barry‘}
58
59 # 删,清空
60
61 set1.clear()
62
63 print(set1) # set() 表示空集合
64
65 # 删,删除整个集合
66
67 # del set1
68
69
70 # 没有改,因为集合里面存的内容是不可变的
71
72 set1 = {‘alex‘, ‘wusir‘, ‘ritian‘, ‘egon‘, ‘barry‘, ‘alex‘}
73 # 查
74 for i in set1:
75 print(i)
76
77 # 交集
78 set1 = {1, 2, 3, 4, 5}
79 set2 = {4, 5, 6, 7, 8}
80
81 print(set1 & set2) # {4, 5}
82 print(set1.intersection(set2)) # {4, 5}
83
84
85 # 并集
86 set1 = {1, 2, 3, 4, 5}
87 set2 = {4, 5, 6, 7, 8}
88
89 print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8}
90 print(set2.union(set1)) # {1, 2, 3, 4, 5, 6, 7, 8}
91
92
93 # 反交集
94 set1 = {1, 2, 3, 4, 5}
95 set2 = {4, 5, 6, 7, 8}
96
97 print(set1 ^ set2) # {1, 2, 3, 6, 7, 8}
98 print(set1.symmetric_difference(set2)) # {1, 2, 3, 6, 7, 8}
99
100 # 差集 set1 - set2 得到set1独有的
101 set1 = {1, 2, 3, 4, 5}
102 set2 = {4, 5, 6, 7, 8}
103
104 print(set1 - set2) # {1, 2, 3}
105 print(set1.difference(set2)) # {1, 2, 3}
106
107 # 子集与超集 set1 set2 为True,则set1是set2的超集
108 set1 = {1, 2, 3}
109 set2 = {1, 2, 3, 4, 5, 6}
110
111 print(set1 # True
112 print(set1.issubset(set2)) # True
113
114 print(set1 > set2) # False
115
116
117
118
119 # 面试题:使用集合将list去重
120 li = [1, 22, 33, 22, 44, 55, 33]
121
122 li = list(set(li)) # set后返回的是集合set类型,需要强转成list
123
124 print(li) # [1, 44, 55, 22, 33]
125
126
127
128 # 集合本身是可变数据类型,但是内部元素是不可变数据类型
129 # 如何将集合变为不可变集合,使用frozenset让集合变为不可变集合,frozenset是不可变集合数据类型,也是无序的
130
131 s = frozenset(‘python‘)
132 print(s) # frozenset({‘o‘, ‘t‘, ‘p‘, ‘h‘, ‘n‘, ‘y‘})
133
134 s1 = {1, 2, 3}
135 s2 = frozenset(s1)
136 print(s1, type(s1)) # {1, 2, 3}
137 print(s2, type(s2)) # frozenset({1, 2, 3})
138
139 # frozenset集合,不能增加和删,只能查,只读集合
140 for i in s2:
141 print(i)
View Code
Python集合
标签:图片 自动 style inter 需要 div splay 删除 不能
原文地址:https://www.cnblogs.com/whylinux/p/9537712.html