python集合

特点:去重、关系测试;无序的 ;

功能:增、删、查

应用范围

    1. python班的同学和运维班的同学   其中有同学两个班都报了, 现在要把两个班的同学合并,不能有重复。(求两个列表的并集)

    2. python班的同学和运维班的同学   其中有同学两个班都报了,现在要把两个班都报的同学取出来。(取两个列表的交集)

1
2
3
4
5
6
7
8
9
10
#格式:
set_1 
= 
{
1
2
3
4
5
6
}
 
#例如去重:
list_1 
= 
[
1
,
2
,
3
,
4
,
5
,
6
,
1
]
list_1 
= 
set
(list_1)            
#列表转集合
 
print
(list_1,
type
(list_1))      
#打印出来的时候已经没有重复的。
 
输出:{
1
2
3
4
5
6
} <
class 
'set'
>

集合的所有关系测试

求交集(两个列表都有的)

1
2
3
4
list_1 
= 
[
1
,
2
,
3
,
4
,
5
,
6
,
1
]
list_1 
= 
set
(list_1)
list_2 
= 
set
([
7
,
8
,
9
,
0
,
1
,
2
])
print
(list_1.intersection(list_2))

求并集(两个列表合并)

1
print
(list_1.union(list_2))

求差集(A有,B相对于A没有的)

1
2
print
(list_1.difference(list_2))    
#list_1 里边有的,list_2相对于list_1里边没有的;
print
(list_2.difference(list_1))    
#list_2 里边有的,list_1相对于list_2里边没有的;

取子集(两个列表有相同的)

1
2
list_3 
= 
set
([
1
,
2
])
print
(list_3.issubset(list_1))

求父集(两个列表有相同的)

1
print
(list_1.issuperset(list_3))

对称差集(把两个列表里边去掉重复的,其他的都取出来)

1
print
(list_1.symmetric_difference(list_2))

判断两个列表有没有交集

1
2
list_4 
= 
set
([
3
,
4
])
print
(list_3.isdisjoint(list_4))

运算符求所有关系测试

#交集

print(list_1 & list_2)

#并集

print(list_1 | list_2)

#差集

print(list_1 - list_2)

#对称差集

print(list_1 ^ list_2 )

集合基本操作

添加

1
2
list_1.add(
99
)
print
(list_1)

添加多项

1
2
list_1.update([
11
,
22
,
33
])
print
(list_1)

删除(一次只能删除一个)删除的元素不存在 会报错;正常删除一个元素返回一个None 。

1
2
list_1.remove(
1
)
print
(list_1)

任意删除一个元素,并且返回删除的元素;如果没有返回None 。

1
print
(list_1.pop())

指定删除一个元素,如果没有元素也不报错,始终返回值为None;

1
print
(list_1.discard(
1
))

查看集合长度

1
print
(
len
(list_1))

x在不在集合里

1
print
(
2 
in 
list_1)

x是不是不在集合里

1
print
(
1 
not 
in 
list_1)