在 Python 中,set
是一种内置的数据类型,用于存储不重复的元素。set
是无序的,这意味着元素没有特定的顺序。set
提供了一些有用的方法和操作,可以用于集合运算,如并集、交集、差集等。
创建集合
你可以使用花括号 {}
或 set()
函数来创建集合。
# 使用花括号创建集合
fruits = {"apple", "banana", "cherry"}
print(fruits) # 输出: {'apple', 'banana', 'cherry'}
# 使用 set() 函数创建集合
numbers = set([1, 2, 3, 4, 5])
print(numbers) # 输出: {1, 2, 3, 4, 5}
基本操作
添加元素
使用 add()
方法可以向集合中添加元素。
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits) # 输出: {'apple', 'banana', 'cherry'}
移除元素
使用 remove()
或 discard()
方法可以从集合中移除元素。remove()
方法在元素不存在时会引发 KeyError
异常,而 discard()
方法不会。
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits) # 输出: {'apple', 'cherry'}
# 使用 discard() 方法
fruits.discard("banana") # 不会引发异常
print(fruits) # 输出: {'apple', 'cherry'}
清空集合
使用 clear()
方法可以清空集合。
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits) # 输出: set()
集合运算
并集
使用 union()
方法或 |
运算符可以计算两个集合的并集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # 输出: {1, 2, 3, 4, 5}
# 使用 | 运算符
union_set = set1 | set2
print(union_set) # 输出: {1, 2, 3, 4, 5}
交集
使用 intersection()
方法或 &
运算符可以计算两个集合的交集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # 输出: {3}
# 使用 & 运算符
intersection_set = set1 & set2
print(intersection_set) # 输出: {3}
差集
使用 difference()
方法或 -
运算符可以计算两个集合的差集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # 输出: {1, 2}
# 使用 - 运算符
difference_set = set1 - set2
print(difference_set) # 输出: {1, 2}
对称差集
使用 symmetric_difference()
方法或 ^
运算符可以计算两个集合的对称差集。
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # 输出: {1, 2, 4, 5}
# 使用 ^ 运算符
symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # 输出: {1, 2, 4, 5}
其他方法
判断元素是否在集合中
使用 in
关键字可以判断元素是否在集合中。
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # 输出: True
print("grape" in fruits) # 输出: False
集合长度
使用 len()
函数可以获取集合的长度。
fruits = {"apple", "banana", "cherry"}
print(len(fruits)) # 输出: 3
总结
set
是一种无序且不重复的集合类型。- 可以使用
{}
或set()
创建集合。 - 提供了添加、移除、清空等基本操作。
- 支持并集、交集、差集