🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Python 集 > 原文: [http://zetcode.com/python/set/](http://zetcode.com/python/set/) Python `set`教程介绍了 Python `set`集合。 我们展示了如何创建集并对其执行操作。 ## Python 集 Python 集是无序数据集,没有重复的元素。 集支持数学中已知的诸如并集,相交或求差的运算。 ## Python 集字面值 从 Python 2.6 开始,可以使用字面值符号创建集。 我们使用大括号在 Python 中定义一个集,并且元素之间用逗号分隔。 `python_set_literal.py` ```py #!/usr/bin/python3 nums = { 1, 2, 2, 2, 3, 4 } print(type(nums)) print(nums) ``` 该示例创建带有字面值符号的 Python 集。 ```py nums = { 1, 2, 2, 2, 3, 4 } ``` 集是唯一元素的集; 即使我们提供了 3 次值 2,该集也只包含一个 2。 ```py $ ./python_set_literal.py <class 'set'> {1, 2, 3, 4} ``` 这是输出。 ## Python 集函数 Python `set()`函数创建一个新集,其元素来自可迭代对象。 可迭代对象是我们可以迭代的对象; 例如字符串或列表。 `python_set_fun.py` ```py #!/usr/bin/python3 seasons = ["spring", "summer", "autumn", "winter"] myset = set(seasons) print(myset) ``` 在示例中,我们使用`set()`内置函数从列表创建了一个集。 ```py $ ./python_set_fun.py {'summer', 'autumn', 'winter', 'spring'} ``` 这是输出。 ## Python 集成员性测试 `in`和`not in`运算符测试集中元素的存在。 `python_set_membership.py` ```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)) ``` 我们使用成员运算符检查集中是否存在两个单词。 ```py $ ./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` ```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)) ``` 在示例中,我们对一组整数值应用了五个内置函数。 ```py print("Number of elements: {0}".format(len(nums))) ``` `len()`方法返回集中的元素数。 ```py print("Minimum: {0}".format(min(nums))) ``` `min()`方法返回集中的最小值。 ```py print("Maximum: {0}".format(max(nums))) ``` `max()`方法返回集中的最大值。 ```py print("Sum: {0}".format(sum(nums))) ``` `sum()`方法返回集中值的总和。 ```py print(sorted(nums)) ``` 最后,使用`sorted()`方法,我们可以从集中创建无序列表。 ```py $ ./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` ```py #!/usr/bin/python3 words = { "spring", "table", "cup", "bottle", "coin" } for word in words: print(word) ``` 在示例中,我们遍历该集并逐个打印其元素。 ```py $ ./python_set_iteration.py table cup coin spring bottle ``` 这是输出。 ## Python 集添加 Python set `add()`方法将新元素添加到集中。 `python_set_add.py` ```py #!/usr/bin/python3 words = { "spring", "table", "cup", "bottle", "coin" } words.add("coffee") print(words) ``` 我们有一套话。 我们使用`add()`方法添加一个新单词。 ```py $ ./python_set_add.py {'table', 'coffee', 'coin', 'spring', 'bottle', 'cup'} ``` 这是输出。 ## Python 集更新 Python set `update()`方法将一个或多个可迭代对象添加到集中。 `python_set_update.py` ```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()`方法将第二组和第三组添加到第一组。 ```py $ ./python_set_update.py {'spring', 'bottle', 'cup', 'coin', 'purse', 'wind', 'nice', 'car', 'table', 'prime', 'puppy'} ``` 这是输出。 ## Python 集删除 Python 有两种删除元素的基本方法:`remove()`和`discard()`。 `remove()`方法从集中删除指定的元素,如果元素不在集中,则提高`KeyError`。 `discard()`方法从集中删除元素,如果要删除的元素不在集中,则不执行任何操作。 `python_set_remove.py` ```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()`删除集元素。 ```py try: words.remove("cloud") except KeyError as e: pass ``` 如果我们没有抓住`KeyError`,脚本将终止而不执行最后一条语句。 ```py $ ./python_set_remove.py {'table', 'cup', 'bottle', 'spring'} {'table', 'bottle', 'spring'} ``` 这是输出。 ## Python 集弹出&清除 `pop()`方法从集中移除并返回任意元素。 `clear()`方法从集中删除所有元素。 `python_set_remove2.py` ```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()`从集中删除所有元素。 ```py $ ./python_set_remove2.py water pen {'cup', 'spring', 'table', 'bottle', 'coin'} set() ``` 这是输出。 ## Python 集运算 使用 Python 集,我们可以执行特定的运算:并集,交集,差和对称差。 `python_set_operations.py` ```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)) ``` 该示例显示了四个设置操作。 ```py print("intersection:", set1.intersection(set2)) ``` `intersection()`方法执行相交操作,该操作返回`set1`和`set2`中的元素。 ```py print("union:", set1.union(set2)) ``` `union()`方法执行联合操作,该操作返回两个集中的所有元素。 ```py print("difference:", set1.difference(set2)) ``` `difference()`方法执行差分操作,该操作返回`set1`中而不是`set2`中的元素。 ```py print("symmetric difference:", set1.symmetric_difference(set2)) ``` `symmetric_difference()`方法执行对称差分操作,该操作返回`set1`或`set2`中的元素,但不返回两者中的元素。 ```py $ ./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` ```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` ```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()`方法。 ```py if (set2.issubset(set1)): print("set1 is a subset of set2") ``` 使用`issubset()`方法,我们检查`set2`是否是`s1`的子集。 ```py if (set1.issuperset(set2)): print("set1 is a superset of set2") ``` 使用`issuperset()`方法,我们检查`set1`是否是`s2`的超集。 ```py if (set2.isdisjoint(set3)): print("set2 and set3 have no common elements") ``` 使用`isdisjoint()`方法,我们检查`set2`和`set3`是否没有共同的元素。 ```py $ ./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()`函数创建的。 ```py >>> 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 教程](/lang/python/), [Python lambda 函数](/python/lambda/), [Python `for`循环](/python/forloop/), [Python 列表推导](/articles/pythonlistcomprehensions/), [Python 映射教程](/python/map/), [OpenPyXL 教程](/articles/openpyxl/), [Python Requests 教程](/web/pythonrequests/)和 [Python CSV 教程](/python/csv/)。