Python 集合
最后修改于 2024 年 1 月 29 日
Python set 教程介绍了 Python 的 set 集合。我们展示了如何创建集合以及对它们进行操作。
Python 集合
Python set 是一个无序的、不包含重复元素的集合。集合支持集合论中的运算,如并集、交集或差集。
Python set 字面量
可以使用字面量表示法创建集合。我们在 Python 中使用花括号来定义集合,元素之间用逗号分隔。
#!/usr/bin/python
nums = { 1, 2, 2, 2, 3, 4 }
print(type(nums))
print(nums)
该示例使用字面量表示法创建了一个 Python 集合。
nums = { 1, 2, 2, 2, 3, 4 }
集合是唯一元素的集合;即使我们提供了三次值 2,集合中也只会包含一个 2。
$ ./python_set_literal.py
<class 'set'>
{1, 2, 3, 4}
Python set 函数
Python 的 set 函数创建一个新的集合,其元素来自一个可迭代对象。可迭代对象是我们能够迭代的对象;例如字符串或列表。
#!/usr/bin/python seasons = ["spring", "summer", "autumn", "winter"] myset = set(seasons) print(myset)
在示例中,我们使用内置的 set 函数从列表中创建了一个集合。
$ ./python_set_fun.py
{'summer', 'autumn', 'winter', 'spring'}
Python set 成员测试
in 和 not in 运算符用于测试元素是否存在于集合中。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin" }
word = 'cup'
if (word in words):
print("{0} is present in the set".format(word))
else:
print("{0} is not present in the set".format(word))
word = 'tree'
if (word not in words):
print("{0} is not present in the set".format(word))
else:
print("{0} is present in the set".format(word))
我们使用成员运算符检查两个单词是否在集合中。
$ ./python_set_membership.py cup is present in the set tree is not present in the set
Python set 内置函数
有几个内置的 Python 函数,如 len 或 min,可以用于 Python 集合。
#!/usr/bin/python
nums = { 21, 11, 42, 29, 22, 71, 18 }
print(nums)
print("Number of elements: {0}".format(len(nums)))
print("Minimum: {0}".format(min(nums)))
print("Maximum: {0}".format(max(nums)))
print("Sum: {0}".format(sum(nums)))
print("Sorted elements:")
print(sorted(nums))
在示例中,我们将五个内置函数应用于一个整数集合。
print("Number of elements: {0}".format(len(nums)))
len 方法返回集合中元素的数量。
print("Minimum: {0}".format(min(nums)))
min 方法返回集合中的最小值。
print("Maximum: {0}".format(max(nums)))
max 方法返回集合中的最大值。
print("Sum: {0}".format(sum(nums)))
sum 方法返回集合中值的总和。
print(sorted(nums))
最后,使用 sorted 方法,我们可以从无序的集合创建一个有序列表。
$ ./python_set_builtins.py
{71, 42, 11, 18, 21, 22, 29}
Number of elements: 7
Minimum: 11
Maximum: 71
Sum: 214
Sorted elements:
[11, 18, 21, 22, 29, 42, 71]
Python set 迭代
可以使用 for 循环迭代 Python 集合。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin" }
for word in words:
print(word)
在示例中,我们遍历集合并逐个打印其元素。
$ ./python_set_iteration.py table cup coin spring bottle
Python set add
Python 集合的 add 方法将新元素添加到集合中。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin" }
words.add("coffee")
print(words)
我们有一个单词集合。我们使用 add 方法添加了一个新单词。
$ ./python_set_add.py
{'table', 'coffee', 'coin', 'spring', 'bottle', 'cup'}
Python set update
Python 集合的 update 方法将一个或多个可迭代对象添加到集合中。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin" }
words.add("coffee")
print(words)
words2 = { "car", "purse", "wind" }
words3 = { "nice", "prime", "puppy" }
words.update(words2, words3)
print(words)
我们有三个单词集合。我们使用 update 方法将第二个和第三个集合添加到第一个集合中。
$ ./python_set_update.py
{'spring', 'bottle', 'cup', 'coin', 'purse', 'wind', 'nice', 'car',
'table', 'prime', 'puppy'}
Python set remove
Python 有两种基本的删除元素的方法:remove 和 discard。remove 方法从集合中删除指定元素,如果元素不在集合中则引发 KeyError。discard 方法从集合中删除元素,如果要删除的元素不在集合中则不执行任何操作。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin" }
words.discard("coin")
words.discard("pen")
print(words)
words.remove("cup")
try:
words.remove("cloud")
except KeyError as e:
pass
print(words)
在示例中,我们使用 remove 和 discard 删除集合元素。
try:
words.remove("cloud")
except KeyError as e:
pass
如果我们没有捕获 KeyError,脚本将在不执行最后一条语句的情况下终止。
$ ./python_set_remove.py
{'table', 'cup', 'bottle', 'spring'}
{'table', 'bottle', 'spring'}
Python set pop & clear
pop 方法从集合中删除并返回一个任意元素。clear 方法删除集合中的所有元素。
#!/usr/bin/python
words = { "spring", "table", "cup", "bottle", "coin", "pen", "water" }
print(words.pop())
print(words.pop())
print(words)
words.clear()
print(words)
在示例中,我们删除并打印了两个随机元素,并显示了剩余的元素。然后我们使用 clear 方法清空集合。
$ ./python_set_remove2.py
water
pen
{'cup', 'spring', 'table', 'bottle', 'coin'}
set()
Python set 操作
使用 Python 集合,我们可以执行特定的操作:并集、交集、差集和对称差集。
#!/usr/bin/python
set1 = { 'a', 'b', 'c', 'c', 'd' }
set2 = { 'a', 'b', 'x', 'y', 'z' }
print("Set 1:", set1)
print("Set 2:", set2)
print("intersection:", set1.intersection(set2))
print("union:", set1.union(set2))
print("difference:", set1.difference(set2))
print("symmetric difference:", set1.symmetric_difference(set2))
该示例展示了四种集合操作。
print("intersection:", set1.intersection(set2))
intersection 方法执行交集操作,返回同时存在于 set1 和 set2 中的元素。
print("union:", set1.union(set2))
union 方法执行并集操作,返回两个集合中的所有元素。
print("difference:", set1.difference(set2))
difference 方法执行差集操作,返回存在于 set1 但不存在于 set2 中的元素。
print("symmetric difference:", set1.symmetric_difference(set2))
symmetric_difference 方法执行对称差集操作,返回存在于 set1 或 set2 中,但不同时存在于两者中的元素。
$ ./python_set_operations.py
Set 1: {'c', 'b', 'a', 'd'}
Set 2: {'y', 'b', 'a', 'x', 'z'}
intersection: {'b', 'a'}
union: {'b', 'a', 'z', 'c', 'x', 'y', 'd'}
difference: {'c', 'd'}
symmetric difference: {'z', 'c', 'x', 'y', 'd'}
可以使用 &、|、- 和 ^ 运算符执行这些操作。
#!/usr/bin/python
set1 = { 'a', 'b', 'c', 'c', 'd' }
set2 = { 'a', 'b', 'x', 'y', 'z' }
print("Set 1:", set1)
print("Set 2:", set2)
print("intersection:", set1 & set2)
print("union:", set1 | set2)
print("difference:", set1 - set2)
print("symmetric difference:", set1 ^ set2)
该示例使用运算符展示了四种集合操作。
子集与超集
如果集合 A 的所有元素都包含在集合 B 中,则 A 称为 B 的子集,B 称为 A 的超集。
#!/usr/bin/python
set1 = { 'a', 'b', 'c', 'd', 'e' }
set2 = { 'a', 'b', 'c' }
set3 = {'x', 'y', 'z' }
if (set2.issubset(set1)):
print("set2 is a subset of set1")
if (set1.issuperset(set2)):
print("set1 is a superset of set2")
if (set2.isdisjoint(set3)):
print("set2 and set3 have no common elements")
在示例中,我们使用了 issubset、issuperset 和 isdisjoint 方法。
if (set2.issubset(set1)):
print("set1 is a subset of set2")
使用 issubset 方法,我们检查 set2 是否是 s1 的子集。
if (set1.issuperset(set2)):
print("set1 is a superset of set2")
使用 issuperset 方法,我们检查 set1 是否是 s2 的超集。
if (set2.isdisjoint(set3)):
print("set2 and set3 have no common elements")
使用 isdisjoint 方法,我们检查 set2 和 set3 是否没有共同元素。
$ ./python_subset_superset.py set1 is a subset of set2 set1 is a superset of set2 set2 and set3 have no common elements
Python 不可变集合
不可变集合(不能修改的集合)使用 frozenset 函数创建。
>>> s1 = frozenset(('blue', 'green', 'red'))
>>> s1
frozenset({'red', 'green', 'blue'})
>>> s1.add('brown')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
当我们尝试向冻结集合添加新元素时会出现错误。
来源
在本文中,我们研究了 Python 的 set 集合。
作者
列出所有 Python 教程。