CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day07/set1.py
Views: 729
1
"""
2
定义和使用集合
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-06
7
"""
8
9
10
def main():
11
set1 = {1, 2, 3, 3, 3, 2}
12
print(set1)
13
print('Length =', len(set1))
14
set2 = set(range(1, 10))
15
print(set2)
16
set1.add(4)
17
set1.add(5)
18
set2.update([11, 12])
19
print(set1)
20
print(set2)
21
set2.discard(5)
22
# remove的元素如果不存在会引发KeyError
23
if 4 in set2:
24
set2.remove(4)
25
print(set2)
26
# 遍历集合容器
27
for elem in set2:
28
print(elem ** 2, end=' ')
29
print()
30
# 将元组转换成集合
31
set3 = set((1, 2, 3, 3, 2, 1))
32
print(set3.pop())
33
print(set3)
34
35
36
if __name__ == '__main__':
37
main()
38
39