阅读量:69
- 添加元素 可以使用add()方法向set中添加一个元素。
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
- 删除元素 可以使用remove()或discard()方法删除set中的元素。
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
- 清空set 可以使用clear()方法清空set中的所有元素。
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
- 求交集 可以使用intersection()或&操作符求两个set的交集。
set1 = {1, 2, 3}
set2 = {2, 3, 4}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {2, 3}
- 求并集 可以使用union()或|操作符求两个set的并集。
set1 = {1, 2, 3}
set2 = {2, 3, 4}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4}
- 求差集 可以使用difference()或-操作符求两个set的差集。
set1 = {1, 2, 3}
set2 = {2, 3, 4}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1}
这些是set常用的操作,还有其他一些操作可以参考Python官方文档。