使用 Python 集合

在 Python 中,集合是唯一项的无序集合。当您需要存储多个值但不关心这些值的顺序并且希望确保没有重复元素时,集合非常有用。

创建集

要创建集合,请使用花括号 {} 或 set() 函数。以下是一些示例:

# Using curly braces
my_set = {1, 2, 3, 4, 5}

# Using the set() function
another_set = set([1, 2, 3, 4, 5])

添加和删​​除元素

要将元素添加到集合中,请使用 add() 方法。要删除元素,可以使用 remove()discard()。它们之间的区别在于,如果元素不存在,remove() 将引发 KeyError,而 discard() 则不会。

# Adding elements
my_set.add(6)

# Removing elements
my_set.remove(5)  # Will raise KeyError if 5 is not in the set
my_set.discard(10)  # Will not raise an error

集合运算

Python 集合支持各种运算,例如并集、交集、差集和对称差集。以下是它们的使用方法:

# Union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # or set1 | set2

# Intersection
intersection_set = set1.intersection(set2)  # or set1 & set2

# Difference
difference_set = set1.difference(set2)  # or set1 - set2

# Symmetric Difference
symmetric_difference_set = set1.symmetric_difference(set2)  # or set1 ^ set2

集合推导

就像列表推导一样,Python 也支持集合推导。这些允许您基于现有的可迭代对象创建集合。以下是示例:

# Creating a set of squares
squares = {x ** 2 for x in range(10)}

结论

集合是 Python 中处理唯一元素集合的一种强大而灵活的方法。了解如何有效地使用集合将帮助您高效轻松地管理数据和执行操作。