Python 中的集合
集合是 Python 中的一种内置数据结构,表示唯一项的无序集合。集合对于涉及成员资格测试、消除重复条目以及执行数学集运算(如 union、intersection 和 difference)的操作特别有用。由于它们的特性,集合是数据分析和操作中的宝贵工具。
1. 创建 Sets
可以通过将项目放在大括号 {} 内或使用 set() 构造函数来创建集合。根据定义,集不允许重复值。
示例:创建简单集
# Creating a set of cars
cars = {"BMW", "Cadillac", "Ford"}
print(cars)
输出:
{'BMW', 'Ford', 'Cadillac'}
(注意:由于 sets 未排序,因此项目的顺序可能会有所不同。
3–2.添加和删除元素
集合允许您使用 add() 和 remove() 方法添加或删除元素。使用 remove() 时,建议确保 set 中存在该项目,以避免 KeyError。可以使用 discard() 删除项目,如果未找到该项目,则不会引发错误。
示例:添加和删除元素
# Creating a set of operating systems
operating_systems = {"Windows", "macOS", "Linux"}
# Adding an element
operating_systems.add("Ubuntu")
# Removing an element
operating_systems.remove("Windows") # Raises KeyError if 'Windows' is not found
# operating_systems.discard("Windows") # Safely removes 'Windows' if it exists
print(operating_systems)
输出:
{'macOS', 'Ubuntu', 'Linux'}
3. 集合操作
集支持各种操作,例如并集、交集、差集和对称差集。可以使用方法或运算符执行这些操作。
示例:Set Operations
# Defining two sets
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# Union of two sets
union_set = set_a | set_b # or set_a.union(set_b)
# Intersection of two sets
intersection_set = set_a & set_b # or set_a.intersection(set_b)
# Difference of two sets
difference_set = set_a - set_b # or set_a.difference(set_b)
# Symmetric difference (items in either set, but not in both)
symmetric_difference_set = set_a ^ set_b # or set_a.symmetric_difference(set_b)
print("Union:", union_set)
print("Intersection:", intersection_set)
print("Difference:", difference_set)
print("Symmetric Difference:", symmetric_difference_set)
输出:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
Symmetric Difference: {1, 2, 5, 6}
3-4. 会员测试
集提供了一种使用 in 关键字测试成员资格的快速方法。由于 sets 的底层哈希表实现,此操作通常比检查列表或 Tuples 中的成员资格更有效。
示例:成员身份测试
# Creating a set of numbers
numbers = {1, 2, 3, 4, 5}
# Testing membership
is_three_in_set = 3 in numbers # True
is_six_in_set = 6 in numbers # False
print("Is 3 in numbers?", is_three_in_set)
print("Is 6 in numbers?", is_six_in_set)
输出:
Is 3 in numbers? True
Is 6 in numbers? False
3-5. 集合推导式
与列表推导式类似,Python 也支持集合推导式,允许集合的简洁易读构造。
示例:Set Comprehension
# Creating a set of squares for even numbers from 0 to 9
squares = {x**2 for x in range(10) if x % 2 == 0}
print(squares) # Outputs a set of squares of even numbers
输出:
{0, 4, 16, 36, 64}