Python—集合

集合set

集合是可变数据类型,集合内的元素必须是不可变数据类型;集合是无序的并且集合内的元素必须是不重复的。

增:

add—向集合内添加数据

set1 = set() #创建一个空的集合

set1.add('nero') #向集合内添加数据

update—向集合内迭代添加数据

set1 = set()

set1.update('abc') #向集合内迭代添加数据
>>>{'a', 'b', 'c'}

删:

pop—随机删除集合内的一个数据

set1 = {'c5',22,53,'a',44,'b','nero'}

set1.pop() #随机删除集合内的一个数据
>>>{'c5', 53, 22, 'b', 'a', 'nero'}

remove—删除指定数据,如该数据不存在则报错

set1 = {'c5',22,53,'a',44,'b','nero'}

set1.remove('nero') #删除指定数据,如该数据不存在则报错
>>>{'a', 44, 53, 'c5', 22, 'b'}

clear—清空集合

set1 = {'c5',22,53,'a',44,'b','nero'}

set1.clear() #清空集合
>>>set()

del—删除整个集合

del set1 #删除整个集合

>>>NameError: name 'set1' is not defined

查:

查询集合内的数据,只能使用for循环

交集(&或intersection)

set1 = {'c5',22,53,'a',44,'b','nero'}
set2 = {5,22,53,8,'c5',10,'d3','jason'}
set3 = {53,'c5',99,57}

print(set1 & set2 & set3) #返回多个集合之间相同的数据
>>>{'c5', 53}

print(set1.intersection(set2.intersection(set3))) #等同于&
>>>{'c5', 53}

并集(|或union)

set1 = {'c5',22,53,'a',44,'b','nero'}
set2 = {5,22,53,8,'c5',10,'d3','jason'}
set3 = {53,'c5',99,57}

print(set1 | set2 | set3) #将多个集合合并,除去重复数据
>>>{'nero', 'jason', 99, 'd3', 5, 8, 10, 44, 'c5', 53, 'a', 22, 'b', 57}

print(set1.union(set2.union(set3))) #等同于|
>>>{'b', 'nero', 5, 8, 10, 22, 'c5', 99, 'jason', 44, 'a', 53, 'd3', 57}

反交集(^或symmetric_difference)

set1 = {'c5',22,53,'a',44,'b','nero'}
set2 = {5,22,53,8,'c5',10,'d3','jason'}

print(set1 ^ set2) #去除两个集合内都有的数据后,进行合并,多次反交集运算应注意运算规则,如三个集合反交集,set3内与set1、set2都有的数据还会加入到最终的结果中

print(set1.symmetric_difference(set2)) #等同于 ^
>>>{5, 'jason', 8, 10, 'd3', 44, 'b', 'a', 'nero'}

差集

set1 = {'c5',22,53,'a',44,'b','nero'}
set2 = {5,22,53,8,'c5',10,'d3','jason'}

print(set1 - set2) # == set1-(两个集合都有的数据),set1并不会与set2的数据合并
>>>{'b', 'nero', 44, 'a'}

子集与超集

#子集
set1 = {'c5',22,53}
set2 = {5,22,53,8,'c5',10,'d3','jason'}

print(set1 < set2) #判断set1是否为set2的子集,也就是判断set2中是否包含了set1所有的数据,返回布尔值
>>>True

print(set1.issubset(set2)) #等同于 <

#超集
print(set2 > set1) #判断set2是否为set1的超集,返回布尔值
>>>True

print(set2.issuperset(set1)) #等同于 >

不可变集合

set4 = frozenset('hello  nero') #创建名为set4的不可变集合,并迭代添加数据到集合内,去重

print(set4) 
>>>frozenset({'o', 'e', 'l', ' ', 'r', 'h', 'n'})

lis1 = [0,1,1,1,0,2,3,3,4,4,5,5,6,6,8,8]
set4 = frozenset(lis1) #将列表转换成不可变集合set4
lis = list(set4) #再将不可变集合转换成列表,这个列表已经去除了重复数据
print(set4)
>>>frozenset({0, 1, 2, 3, 4, 5, 6, 8})
print(lis)
>>>[0, 1, 2, 3, 4, 5, 6, 8]

枚举

lis1 = [1,2,3,4]

for index,vlaue in enumerate(lis1): #enumerate同时返回元素的索引和元素,可设置索引,默认位置是0
    print(index,vlaue)
>>>
0 1
1 2
2 3
3 4    

for index,vlaue in enumerate('hello nero',1):
    print(index,vlaue)
>>>
1 h
2 e
3 l
4 l
5 o
6  
7 n
8 e
9 r
10 o
原文地址:https://www.cnblogs.com/NeroCl/p/8086620.html