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

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

Python 集

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

Python 集字面值

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

python_set_literal.py

  1. #!/usr/bin/python3
  2. nums = { 1, 2, 2, 2, 3, 4 }
  3. print(type(nums))
  4. print(nums)

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

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

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

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

这是输出。

Python 集函数

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

python_set_fun.py

  1. #!/usr/bin/python3
  2. seasons = ["spring", "summer", "autumn", "winter"]
  3. myset = set(seasons)
  4. print(myset)

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

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

这是输出。

Python 集成员性测试

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

python_set_membership.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin" }
  3. word = 'cup'
  4. if (word in words):
  5. print("{0} is present in the set".format(word))
  6. else:
  7. print("{0} is not present in the set".format(word))
  8. word = 'tree'
  9. if (word not in words):
  10. print("{0} is not present in the set".format(word))
  11. else:
  12. print("{0} is present in the set".format(word))

我们使用成员运算符检查集中是否存在两个单词。

  1. $ ./python_set_membership.py
  2. cup is present in the set
  3. tree is not present in the set

这是输出。

Python 集内置函数

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

python_set_builtins.py

  1. #!/usr/bin/python3
  2. nums = { 21, 11, 42, 29, 22, 71, 18 }
  3. print(nums)
  4. print("Number of elements: {0}".format(len(nums)))
  5. print("Minimum: {0}".format(min(nums)))
  6. print("Maximum: {0}".format(max(nums)))
  7. print("Sum: {0}".format(sum(nums)))
  8. print("Sorted elements:")
  9. print(sorted(nums))

在示例中,我们对一组整数值应用了五个内置函数。

  1. print("Number of elements: {0}".format(len(nums)))

len()方法返回集中的元素数。

  1. print("Minimum: {0}".format(min(nums)))

min()方法返回集中的最小值。

  1. print("Maximum: {0}".format(max(nums)))

max()方法返回集中的最大值。

  1. print("Sum: {0}".format(sum(nums)))

sum()方法返回集中值的总和。

  1. print(sorted(nums))

最后,使用sorted()方法,我们可以从集中创建无序列表。

  1. $ ./python_set_builtins.py
  2. {71, 42, 11, 18, 21, 22, 29}
  3. Number of elements: 7
  4. Minimum: 11
  5. Maximum: 71
  6. Sum: 214
  7. Sorted elements:
  8. [11, 18, 21, 22, 29, 42, 71]

这是输出。

Python 集迭代

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

python_set_iteration.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin" }
  3. for word in words:
  4. print(word)

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

  1. $ ./python_set_iteration.py
  2. table
  3. cup
  4. coin
  5. spring
  6. bottle

这是输出。

Python 集添加

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

python_set_add.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin" }
  3. words.add("coffee")
  4. print(words)

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

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

这是输出。

Python 集更新

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

python_set_update.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin" }
  3. words.add("coffee")
  4. print(words)
  5. words2 = { "car", "purse", "wind" }
  6. words3 = { "nice", "prime", "puppy" }
  7. words.update(words2, words3)
  8. print(words)

我们有三组单词。 我们使用update()方法将第二组和第三组添加到第一组。

  1. $ ./python_set_update.py
  2. {'spring', 'bottle', 'cup', 'coin', 'purse', 'wind', 'nice', 'car',
  3. 'table', 'prime', 'puppy'}

这是输出。

Python 集删除

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

python_set_remove.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin" }
  3. words.discard("coin")
  4. words.discard("pen")
  5. print(words)
  6. words.remove("cup")
  7. try:
  8. words.remove("cloud")
  9. except KeyError as e:
  10. pass
  11. print(words)

在示例中,我们使用remove()discard()删除集元素。

  1. try:
  2. words.remove("cloud")
  3. except KeyError as e:
  4. pass

如果我们没有抓住KeyError,脚本将终止而不执行最后一条语句。

  1. $ ./python_set_remove.py
  2. {'table', 'cup', 'bottle', 'spring'}
  3. {'table', 'bottle', 'spring'}

这是输出。

Python 集弹出&清除

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

python_set_remove2.py

  1. #!/usr/bin/python3
  2. words = { "spring", "table", "cup", "bottle", "coin", "pen", "water" }
  3. print(words.pop())
  4. print(words.pop())
  5. print(words)
  6. words.clear()
  7. print(words)

在示例中,我们删除并打印两个随机元素,并显示其余元素。 然后,使用clear()从集中删除所有元素。

  1. $ ./python_set_remove2.py
  2. water
  3. pen
  4. {'cup', 'spring', 'table', 'bottle', 'coin'}
  5. set()

这是输出。

Python 集运算

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

python_set_operations.py

  1. #!/usr/bin/python3
  2. set1 = { 'a', 'b', 'c', 'c', 'd' }
  3. set2 = { 'a', 'b', 'x', 'y', 'z' }
  4. print("Set 1:", set1)
  5. print("Set 2:", set2)
  6. print("intersection:", set1.intersection(set2))
  7. print("union:", set1.union(set2))
  8. print("difference:", set1.difference(set2))
  9. print("symmetric difference:", set1.symmetric_difference(set2))

该示例显示了四个设置操作。

  1. print("intersection:", set1.intersection(set2))

intersection()方法执行相交操作,该操作返回set1set2中的元素。

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

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

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

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

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

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

  1. $ ./python_set_operations.py
  2. Set 1: {'c', 'b', 'a', 'd'}
  3. Set 2: {'y', 'b', 'a', 'x', 'z'}
  4. intersection: {'b', 'a'}
  5. union: {'b', 'a', 'z', 'c', 'x', 'y', 'd'}
  6. difference: {'c', 'd'}
  7. symmetric difference: {'z', 'c', 'x', 'y', 'd'}

这是一个示例输出。

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

python_set_operations2.py

  1. #!/usr/bin/python3
  2. set1 = { 'a', 'b', 'c', 'c', 'd' }
  3. set2 = { 'a', 'b', 'x', 'y', 'z' }
  4. print("Set 1:", set1)
  5. print("Set 2:", set2)
  6. print("intersection:", set1 & set2)
  7. print("union:", set1 | set2)
  8. print("difference:", set1 - set2)
  9. print("symmetric difference:", set1 ^ set2)

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

子集和超集

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

python_subset_superset.py

  1. #!/usr/bin/python3
  2. set1 = { 'a', 'b', 'c', 'd', 'e' }
  3. set2 = { 'a', 'b', 'c' }
  4. set3 = {'x', 'y', 'z' }
  5. if (set2.issubset(set1)):
  6. print("set2 is a subset of set1")
  7. if (set1.issuperset(set2)):
  8. print("set1 is a superset of set2")
  9. if (set2.isdisjoint(set3)):
  10. print("set2 and set3 have no common elements")

在示例中,我们使用issubset()issuperset()isdisjoint()方法。

  1. if (set2.issubset(set1)):
  2. print("set1 is a subset of set2")

使用issubset()方法,我们检查set2是否是s1的子集。

  1. if (set1.issuperset(set2)):
  2. print("set1 is a superset of set2")

使用issuperset()方法,我们检查set1是否是s2的超集。

  1. if (set2.isdisjoint(set3)):
  2. print("set2 and set3 have no common elements")

使用isdisjoint()方法,我们检查set2set3是否没有共同的元素。

  1. $ ./python_subset_superset.py
  2. set1 is a subset of set2
  3. set1 is a superset of set2
  4. set2 and set3 have no common elements

这是输出。

Python 不可变集

不可变的集(无法修改的集)是使用frozenset()函数创建的。

  1. >>> s1 = frozenset(('blue', 'green', 'red'))
  2. >>> s1
  3. frozenset({'red', 'green', 'blue'})
  4. >>> s1.add('brown')
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. AttributeError: 'frozenset' object has no attribute 'add'

当我们尝试向冻结集中添加新元素时出现错误。

在本教程中,我们使用了 Python set集。

您可能也对以下相关教程感兴趣: Python 教程Python lambda 函数Python for循环Python 列表推导Python 映射教程OpenPyXL 教程Python Requests 教程Python CSV 教程