Python集合教程介绍了Python集合。我们展示了如何创建集合并对其执行操作。
Python集
Pythonset是没有重复元素的无序数据集合。集合支持数学中已知的并集、交集或差集等运算。
Python设置文字
从Python2.6开始,可以使用文字符号创建集合。我们使用大括号在Python中定义集合,元素以逗号分隔。
#!/usr/bin/python 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设置函数
Pythonset
函数创建一个新集合,其元素取自可迭代对象。可迭代对象是我们可以迭代的对象;例如字符串或列表。
#!/usr/bin/python seasons = ["spring", "summer", "autumn", "winter"] myset = set(seasons) print(myset)
在示例中,我们使用set
内置函数从列表创建一个集合。
$ ./python_set_fun.py {'summer', 'autumn', 'winter', 'spring'}
Python集合成员测试
in
和notin
运算符测试集合中是否存在元素。
#!/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设置内置函数
有几个内置的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集合迭代
可以使用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集添加
Pythonsetadd
方法向集合中添加一个新元素。
#!/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集合更新
Pythonsetupdate
方法将一个或多个可迭代对象添加到集合中。
#!/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设置删除
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设置弹出和清除
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集合操作
使用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集集合。
列出所有Python教程。