数据类型的内置方法:集合
数据类型的内置方法:集合
作用
- 用于关系运算的集合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
- 一个值or多个值:多个值,且值为不可变数据类型
- 有序or无序:无序
- 可变or不可变:可变
定义
- {} 内用逗号分隔开多个元素,每个元素必须是不可变类型。
s = {1,2,1,'a'} # s = set({1,2,'a'})
print(s) # {1,2,'a'}
优先掌握的内置方法
1:len 长度
s = {1,2,3}
print(len(s)) # 3
2:成员运算 in 和 not in
s = {1,3,5,'a'}
print('a' in s) # True
print('a' not in s) #False
3:| 并集(union)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'kevin','nick','egon'}
print(pythoners | linuxers)
# {'nick', 'jason', 'jin', 'kevin', 'egon'}
4:& 交集(intersection)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'kevin','nick','egon'}
print(pythoners & linuxers)
# {'egon', 'nick'}
5:- 差集(difference)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'kevin','nick','egon'}
print(pythoners - linuxers)
# {'jin', 'jason'}
6:^ 对称差集(symmetric_difference)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'kevin','nick','egon'}
print(pythoners ^ linuxers)
# {'jason', 'kevin', 'jin'}
7: ==
pythoners = {'jason','nick','egon'}
linuxers = {'jason','nick','egon'}
print(pythoners == linuxers)
# False
8:父集 >,>=,(issuperset)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'nick','egon'}
print(pythoners > linuxers) # True
print(pythoners >= linuxers) # True
9:子集 <,<=,(issubset)
pythoners = {'jason','nick','egon','jin'}
linuxers = {'nick','egon'}
print(linuxers < pythoners) # True
print(linuxers <= pythoners) #True
千里之行,始于足下。