在Python中,集合是一种无序、可变的数据类型,用于存储不重复的元素。Python提供了内置的集合类型 set,以及 frozenset(不可变的集合)。以下是一些Python集合的常见应用场景:
去重:
集合是存储唯一元素的数据结构,因此可以用来去重。通过将列表或其他可迭代对象转换为集合,可以轻松去除重复的元素。
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers) # 输出: {1, 2, 3, 4, 5}
集合运算:
集合支持基本的集合运算,如并集、交集、差集等。
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}
# 并集
union_set = set1.union(set2)
# 交集
intersection_set = set1.intersection(set2)
# 差集
difference_set = set1.difference(set2)
print(union_set) # 输出: {1, 2, 3, 4, 5, 6, 7}
print(intersection_set) # 输出: {3, 4, 5}
print(difference_set) # 输出: {1, 2}
成员检查:
使用集合可以更高效地进行成员检查,因为集合中的元素是唯一的。
fruits = {"apple", "banana", "orange"}
print("banana" in fruits) # 输出: True
print("grape" in fruits) # 输出: False
集合推导式:
类似于列表推导式,Python也支持集合推导式,可以用一行代码快速创建集合。
s

最低0.47元/天 解锁文章
137

被折叠的 条评论
为什么被折叠?



