zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python: set集合方法介绍

2023-06-13 09:12:58 时间

文章背景: 集合(set)是Python中的一个数据类型。在集合中,每个元素都是唯一的(没有重复项),并且必须是不可变的(不能更改)。下面就来介绍set的内置方法。

Python版本:Python 3.7

通过dir(set) 可以得到set的属性和内置方法的列表。

print(dir(set))
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']

可以看出,set有17个内置方法。

1 add()、update()和copy()方法2 remove()、discard()、pop()、clear()方法3 isdisjoint()、issubset()、issuperset()方法4 union()方法5 intersection()、intersection_update()方法6 difference()、difference_update()方法7 symmetric_difference()、symmetric_difference_update()方法

1 add()、update()和copy()方法

set.add(element)

给集合添加元素,如果添加的元素在集合中已存在,则不执行任何操作。

需要注意的是,使用 add() 方法添加的元素,只能是数字、字符串、元组或者布尔类型(True 和 False)值,不能添加列表、字典、集合这类可变的数据,否则 Python 解释器会报 TypeError错误。

a = {1, 2, 3}
a.add((1, 2))
print(a)

a.add([1, 2])
print(a)
{(1, 2), 1, 2, 3}
TypeError: unhashable type: 'list'

set1.update(iterable)

set1是一个集合,并且iterable可以是任何可迭代的对象,例如列表,集合,字典,字符串等。将可迭代的元素添加到集合set1中。

string_alphabet = 'abc'
numbers_set = {1, 2}

# 将字符串的元素添加到集合中
numbers_set.update(string_alphabet)
print('numbers_set =', numbers_set)

info_dictionary = {'key': 1, 'lock': 2}
numbers_set = {'a', 'b'}

# 将字典的键添加到集合中
numbers_set.update(info_dictionary)
print('numbers_set =', numbers_set)
numbers_set = {1, 2, 'c', 'a', 'b'}
numbers_set = {'b', 'key', 'lock', 'a'}

如果将字典传递给update()方法,则将字典的键添加到集合中。

set2 = set1.copy()

拷贝一个集合。

numbers = {1, 2, 3, 4}
new_numbers = numbers.copy()

new_numbers.add('5')

print('numbers: ', numbers)
print('new_numbers: ', new_numbers)
numbers:  {1, 2, 3, 4}
new_numbers:  {1, 2, 3, 4, '5'}

如果在修改新集合时,需要原始集合不变,则可以使用copy()方法。

2 remove()、discard()、pop()、clear()方法

set.remove(item)

set.discard(value)

remove()和discard()方法都是用于移除集合中的指定元素。remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。

a = {1, 2, 3}
a.remove(1)
print(a)

a.remove(1)
print(a)
{2, 3}
KeyError: 1
a = {1, 2, 3}
a.remove(1)
print(a)

a.discard(1)
print(a)
{2, 3}
{2, 3}

set.pop()

随机移除一个元素。

fruits = {"apple", "banana", "cherry"}
x = fruits.pop()

print(x)
print(fruits)
banana
{'cherry', 'apple'}

set.clear()

移除集合中的所有元素。

fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
set()
3 isdisjoint()、issubset()、issuperset()方法

set1.isdisjoint(set2)

判断两个集合是否包含相同的元素,如果没有,返回 True;否则,返回 False。

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "facebook"}

print(x.isdisjoint(y))
True

set1.issubset(set2)

判断set1的所有元素是否都包含在set2中,如果是则返回 True,否则返回 False。

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}

print(x.issubset(y))
True

set1.issuperset(set2)

判断set2的所有元素是否都包含在set1中,如果是则返回 True,否则返回 False。

x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}

print(x.issuperset(y))
True
4 union()方法

set.union(set1, set2...)

返回两个或更多集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。

求两个集合的并集,可以使用运算符:|

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

print(x.union(y))
print(x | y)
{'cherry', 'google', 'runoob', 'apple', 'banana'}
{'cherry', 'google', 'runoob', 'apple', 'banana'}
5 intersection()、intersection_update()方法

set.intersection(set1, set2 ... etc)

返回两个或更多集合中都包含的元素,即交集。

求两个集合的交集,可以使用运算符:&

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

print(x.intersection(y))
print(x & y)
{'apple'}
{'apple'}

set.intersection_update(set1, set2 ... etc)

获取两个或更多集合中都重叠的元素,即计算交集。

intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素。

x = {"apple", "banana", "cherry"}  
y = {"google", "runoob", "apple"}

x.intersection_update(y)
print(x)
{'apple'}
6 difference()、difference_update()方法

set1.difference(set2)

返回集合的差集,即返回的集合元素包含在set1中,但不包含在set2中。

求两个集合的差集,可以使用运算符:-

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

print(x.difference(y))
print(x - y)
{'banana', 'cherry'}
{'banana', 'cherry'}

set.difference_update(set)

移除两个集合中都存在的元素。

difference() 方法返回一个移除相同元素的新集合,而 difference_update() 方法是直接在原来的集合中移除元素,没有返回值。

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.difference_update(y)
print(x)
{'banana', 'cherry'}
7 symmetric_difference()、symmetric_difference_update()方法

set1.symmetric_difference(set2)

返回两个集合中不重复元素的集合,即会移除两个集合中都存在的元素。

求两个集合的对称差集,可以使用运算符:^

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

print(x.symmetric_difference(y))
print(x ^ y)
{'cherry', 'google', 'runoob', 'banana'}
{'cherry', 'google', 'runoob', 'banana'}

set1.symmetric_difference_update(set2)

移除set1在set2中相同的元素,并将set2中不同的元素插入到set1中。

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}

x.symmetric_difference_update(y)
print(x)
{'banana', 'google', 'runoob', 'cherry'}

参考资料:

[1] Python set集合方法详解(全)(http://c.biancheng.net/view/4402.html)

[2] Python set集合基本操作(添加、删除、交集、并集、差集)(http://c.biancheng.net/view/4400.html)

[3] Python set集合详解(http://c.biancheng.net/view/4395.html)

[3] Python3 集合(https://www.runoob.com/python3/python3-set.html)