阅读量:0
在Python中,set()
函数通常用于创建一个集合(set)
- 创建一个空集合:
empty_set = set()
- 使用可迭代对象(如列表、元组等)创建集合:
numbers = [1, 2, 3, 4, 5] number_set = set(numbers) print(number_set) # 输出:{1, 2, 3, 4, 5}
- 去除列表中的重复元素:
duplicates = [1, 2, 2, 3, 4, 4, 5] unique_elements = set(duplicates) print(list(unique_elements)) # 输出:[1, 2, 3, 4, 5]
- 检查两个集合是否相等:
set1 = {1, 2, 3} set2 = {1, 2, 3} print(set1 == set2) # 输出:True
- 检查一个集合是否为另一个集合的子集:
subset = {1, 2} superset = {1, 2, 3, 4, 5} print(subset.issubset(superset)) # 输出:True
- 检查一个集合是否包含另一个集合:
subset = {1, 2} superset = {1, 2, 3, 4, 5} print(superset.issuperset(subset)) # 输出:True
- 计算两个集合的并集:
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # 输出:{1, 2, 3, 4, 5}
- 计算两个集合的交集:
set1 = {1, 2, 3} set2 = {2, 3, 4} intersection_set = set1.intersection(set2) print(intersection_set) # 输出:{2, 3}
- 计算两个集合的差集:
set1 = {1, 2, 3} set2 = {2, 3, 4} difference_set = set1.difference(set2) print(difference_set) # 输出:{1}
- 计算两个集合的对称差集:
set1 = {1, 2, 3} set2 = {2, 3, 4} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # 输出:{1, 4}