030 集合的内置方法
集合类型的内置方法
集合可以理解成一个整体,学习Python的学生可以是一个集合体;学习Linux的学生可以是一个集合体
pythoners = ['jason', 'nick', 'tank', 'sean']
linuxers = ['nick', 'egon', 'kevin']
# 即报名pythoners又报名linux的学生
py_li_list = []
for stu in pythoners:
if stu in linuxers:
py_li_list.append(stu)
print(f"pythoners and linuxers: {py_li_list}")
# pythoners and linuxers: ['nick']
1.用途
集合用于关系运算的结合体,由于集合内的元素无序且集合元素不可重复,因此集合可以去重,但是去重后的集合会打乱原来元素的顺序。
2.定义
在{}内用逗号分隔开多个元素,每个元素必须是不可变类型
age = {18,12,9,21,22}
name = {'nick','egon','rocky'}
3.常用操作+内置方法
**优先掌握**
1.长度len
2.成员运算in/not in
3.|并集、union
4.&交集、intersection
5.-差集、difference
6.补集、symmetric_difference
1.长度len
hobby_set = {'run','read','paly'}
print(len(hobby_set))
# 3
2.成员运算in和not in
hobby_set = {'run','read','paly'}
print('swim' in hobby_set)
# False
print('run' in hobby_set)
# True
3.|并集(union)
hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}
print(hobby_set | hobby_set2)
# {'paly', 'swim', 'read', 'run', 'sing'}
print(hobby_set.union(hobby_set2))
# {'read', 'sing', 'run', 'swim', 'paly'}
4.&交集(intersection)
hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}
print(hobby_set & hobby_set2)
# {'run'}
print(hobby_set.intersection(hobby_set2))
# {'run'}
5.-差集(difference)
hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}
print(hobby_set - hobby_set2)
# {'read', 'paly'}
print(hobby_set.difference(hobby_set2))
# {'read', 'paly'}
6.^补集(symmetric_difference)
hobby_set = {'run','read','paly'}
hobby_set2 = {'run','sing','swim'}
print(hobby_set ^ hobby_set2)
# {'swim', 'sing', 'paly', 'read'}
print(hobby_set.ymmetric_difference(hobby_set2))
# {'swim', 'sing', 'paly', 'read'}
**了解**
1.pop随机删除
2.clear清空
3.update更新
4.copy复制
5.移除remove/discard
remove和discard的区别:
remove在移除集合里没有的元素的时候,程序会报错,而discard不会报错