阅读量:108
set() 是 Python 中的一个内置函数,用于创建一个新的集合(set)对象。集合是一个无序的、不重复的元素序列。
功能
- 去重:当你需要从一个可迭代对象(如列表、元组等)中去除重复元素时,可以使用
set()函数。 - 交集、并集、差集等操作:集合支持多种集合运算,如交集(intersection)、并集(union)、差集(difference)等。
- 成员关系测试:可以使用
in或not in运算符检查一个元素是否在集合中。
用法
- 创建空集合:
empty_set = set()
- 从可迭代对象创建集合:
my_list = [1, 2, 3, 4, 4, 5, 6, 6]
unique_numbers = set(my_list)
print(unique_numbers) # 输出:{1, 2, 3, 4, 5, 6}
-
集合运算:
- 交集:
intersection()方法或&运算符。 - 并集:
union()方法或|运算符。 - 差集:
difference()方法或-运算符。 - 对称差集:
symmetric_difference()方法或^运算符。
- 交集:
示例:
setA = {1, 2, 3, 4}
setB = {3, 4, 5, 6}
# 交集
intersection = setA & setB # 或者 intersection = setA.intersection(setB)
print(intersection) # 输出:{3, 4}
# 并集
union = setA | setB # 或者 union = setA.union(setB)
print(union) # 输出:{1, 2, 3, 4, 5, 6}
# 差集
difference = setA - setB # 或者 difference = setA.difference(setB)
print(difference) # 输出:{1, 2}
# 对称差集
symmetric_difference = setA ^ setB # 或者 symmetric_difference = setA.symmetric_difference(setB)
print(symmetric_difference) # 输出:{1, 2, 5, 6}
- 成员关系测试:
my_set = {1, 2, 3, 4, 5}
print(3 in my_set) # 输出:True
print(6 in my_set) # 输出:False