Python数据类型 ——— 集合

集合

集合(set)是一个无序和无索引的集合,集合中不允许存在重复的成员。

创建集合

创建空集合

通过set()的方式可以创建一个空集合。比如:

a = set()
print(type(a))  # <class 'set'>
print(a)        # set()

需要注意的是,{}表示的是一个空字典,而不是一个空集合。比如:

a = {
    
    }
print(type(a))  # <class 'dict'>
print(a)        # {}

创建非空集合

创建非空集合时可以在{}中设置集合的初始值。比如:

a = {
    
    1, 2, 3, 4, 5}
print(type(a))  # <class 'set'>
print(a)        # {1, 2, 3, 4, 5}

需要注意的是,集合中存放的元素可以是不同类型的。比如:

a = {
    
    2021, 'dragon'}
print(type(a))  # <class 'set'>
print(a)        # {'dargon', 2021}

说明一下:

  • set是一个无序的集合,插入数据的顺序与数据的存储顺序不一定相同。
  • set中存储的元素必须是“可哈希的”,也就是可以计算出一个哈希值。

新增集合元素

add方法

扫描二维码关注公众号,回复: 14556136 查看本文章

使用add方法可以将一个元素添加到集合中。比如:

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

update方法

使用update方法可以将多个元素添加到集合中。比如:

a = {
    
    1, 2, 3, 4}
a.update([5, 6, 7, 8])
print(a)  # {1, 2, 3, 4, 5, 6, 7, 8}

说明一下: 传给update的参数可以是任意的可迭代对象,update方法底层会遍历传入的可迭代对象,将可迭代对象中的元素一个个插入到集合中。

删除集合元素

remove方法

使用remove方法可以指定删除集合中特定值的元素。比如:

a = {
    
    1, 2, 3, 4}
a.remove(2)
# a.remove(5)  # 不存在,抛异常
print(a)  # {1, 3, 4}

注意: 如果要删除的元素不存在,那么程序会抛出异常。

discard方法

使用discard方法也可以指定删除集合中特定值的元素。比如:

a = {
    
    1, 2, 3, 4}
a.discard(2)
a.discard(5)  # 不存在,但不会抛异常
print(a)  # {1, 3, 4}

注意: 与remove方法不同的是,如果要删除的元素不存在,discard方法不会抛出异常。

pop方法

使用pop方法可以删除集合中的最后一项。比如:

a = {
    
    1, 2, 3, 4}
a.pop()
print(a)  # {2, 3, 4}

注意: 集合是无序的,因此使用pop方法时无法预知哪一个元素将会被删除,最终被删除的元素将会作为pop方法的返回值进行返回。

查找集合元素

in和in not操作符

使用in和in not操作符能够判定某个元素是否在集合中存在。比如:

a = {
    
    1, 2, 3, 4}
print(1 in a)       # True
print(10 in a)      # False
print(1 not in a)   # False
print(10 not in a)  # True

遍历集合元素

for循环遍历

集合set是一个可迭代对象,可以直接用for循环对集合中的元素进行遍历。比如:

a = {
    
    1, 2, 3, 4}
for elem in a:
    print(elem)

注意: 集合set是一个无索引的集合,因此无法通过下标来访问集合set中的元素。

合并集合

union方法

使用union方法可以将两个集合合并在一起。比如:

a = {
    
    1, 2, 3}
b = {
    
    4, 5, 6}
c = a.union(b)
print(a)  # {1, 2, 3}
print(b)  # {4, 5, 6}
print(c)  # {1, 2, 3, 4, 5, 6}

注意: union方法会返回合并后的集合,而不会影响两个原有的集合。

update方法

使用update方法可以把一个集合合并到另一个集合中。比如:

a = {
    
    1, 2, 3}
b = {
    
    4, 5, 6}
a.update(b)
print(a)  # {1, 2, 3, 4, 5, 6}
print(b)  # {4, 5, 6}

注意: a.update(b)是把b集合中的元素合并到a集合中,该操作不会修改b集合。

集合常用接口汇总

集合操作:

集合操作 方式
集合检查 inin not
集合长度 len()函数

集合的成员函数:

成员函数 功能
copy 复制集合
clear 清空集合
add 向集合中添加一个元素
update 向集合中添加多个元素(合并集合)
remove 删除指定值的元素(不存在会抛异常)
discard 删除指定值的元素(不存在不会抛异常)
pop 删除集合中的最后一个元素
union 返回两个集合合并后的集合
update 将另一个集合合并到当前集合
difference 返回此集合中不存在于另一个指定集合中的元素所组成的集合
difference_update 删除此集合中存于与另一个指定集合中的元素
intersection 返回两个集合的交集
intersection_update 删除此集合中不存在于另一个指定集合中的元素
isdisjoint 返回两个集合中是否没有交集
issubset 返回此集合是否是另一个指定集合的子集
issuperset 返回此集合是否包含另一个指定集合
symmetric_difference 返回此集合与另一个指定集合的差集
symmetric_difference_update 此集合更新为此集合与另一个指定集合的差集

猜你喜欢

转载自blog.csdn.net/chenlong_cxy/article/details/127531572