my_set = {"rmb","my","ry","hy"} # 添加新元素 my_set.add("java") print(my_set) # 移除元素 my_set.remove("my") print(my_set) # 随机取出一个 element = my_set.pop() print(element) # 清空集合 my_set.clear() print(my_set) # 取出两个集合的差集 set1= {1,2,3} set2 = {2,3,6} setD = set1.difference(set2) print(set1) print(set2) print(setD) # 合并两个集合 set3 = set1.union(set2) print(set3) # 统计集合元素数量len() print(len(set3)) # 集合的遍历 for i in set3: print(i)
输出结果
{'rmb', 'hy', 'java', 'my', 'ry'}
{'rmb', 'hy', 'java', 'ry'}
rmb
set()
{1, 2, 3}
{2, 3, 6}
{1}
{1, 2, 3, 6}
4
1
2
3
6