跳转至

Python 集

原文: http://zetcode.com/python/set/

Python set教程介绍了 Python set集合。 我们展示了如何创建集并对其执行操作。

Python 集

Python 集是无序数据集,没有重复的元素。 集支持数学中已知的诸如并集,相交或求差的运算。

Python 集字面值

从 Python 2.6 开始,可以使用字面值符号创建集。 我们使用大括号在 Python 中定义一个集,并且元素之间用逗号分隔。

python_set_literal.py

#!/usr/bin/python3

nums = { 1, 2, 2, 2, 3, 4 }

print(type(nums))
print(nums)

该示例创建带有字面值符号的 Python 集。

nums = { 1, 2, 2, 2, 3, 4 }

集是唯一元素的集; 即使我们提供了 3 次值 2,该集也只包含一个 2。

$ ./python_set_literal.py 
<class 'set'>
{1, 2, 3, 4}

这是输出。

Python 集函数

Python set()函数创建一个新集,其元素来自可迭代对象。 可迭代对象是我们可以迭代的对象; 例如字符串或列表。

python_set_fun.py

#!/usr/bin/python3

seasons = ["spring", "summer", "autumn", "winter"]

myset = set(seasons)

print(myset)

在示例中,我们使用set()内置函数从列表创建了一个集。

$ ./python_set_fun.py 
{'summer', 'autumn', 'winter', 'spring'}

这是输出。

Python 集成员性测试

innot in运算符测试集中元素的存在。

python_set_membership.py

#!/usr/bin/python3

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 集内置函数

有几个内置 Python 函数,例如len()min(),可以在 Python 集上使用。

python_set_builtins.py

#!/usr/bin/python3

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 集迭代

可以使用for循环来迭代 Python 集。

python_set_iteration.py

#!/usr/bin/python3

words = { "spring", "table", "cup", "bottle", "coin" }

for word in words:

    print(word)

在示例中,我们遍历该集并逐个打印其元素。

$ ./python_set_iteration.py 
table
cup
coin
spring
bottle

这是输出。

Python 集添加

Python set add()方法将新元素添加到集中。

python_set_add.py

#!/usr/bin/python3

words = { "spring", "table", "cup", "bottle", "coin" }

words.add("coffee")

print(words)

我们有一套话。 我们使用add()方法添加一个新单词。

$ ./python_set_add.py 
{'table', 'coffee', 'coin', 'spring', 'bottle', 'cup'}

这是输出。

Python 集更新

Python set update()方法将一个或多个可迭代对象添加到集中。

python_set_update.py

#!/usr/bin/python3

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 集删除

Python 有两种删除元素的基本方法:remove()discard()remove()方法从集中删除指定的元素,如果元素不在集中,则提高KeyErrordiscard()方法从集中删除元素,如果要删除的元素不在集中,则不执行任何操作。

python_set_remove.py

#!/usr/bin/python3

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 集弹出&清除

pop()方法从集中移除并返回任意元素。 clear()方法从集中删除所有元素。

python_set_remove2.py

#!/usr/bin/python3

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 集运算

使用 Python 集,我们可以执行特定的运算:并集,交集,差和对称差。

python_set_operations.py

#!/usr/bin/python3

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()方法执行相交操作,该操作返回set1set2中的元素。

print("union:", set1.union(set2))

union()方法执行联合操作,该操作返回两个集中的所有元素。

print("difference:", set1.difference(set2))

difference()方法执行差分操作,该操作返回set1中而不是set2中的元素。

print("symmetric difference:", set1.symmetric_difference(set2))

symmetric_difference()方法执行对称差分操作,该操作返回set1set2中的元素,但不返回两者中的元素。

$ ./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'}

这是一个示例输出。

可以使用&,|,-和^运算符执行这些操作。

python_set_operations2.py

#!/usr/bin/python3

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)

该示例显示了使用运算符的四个set操作。

子集和超集

如果集 A 的所有元素都包含在集 B 中,则将 A 称为 B 的子集,将 B 称为 A 的超集。

python_subset_superset.py

#!/usr/bin/python3

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()方法,我们检查set2set3是否没有共同的元素。

$ ./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 教程Python lambda 函数Python for循环Python 列表推导Python 映射教程OpenPyXL 教程Python Requests 教程Python CSV 教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组