python基础-集合set的常用方法
set为什么翻译成集合,这个词据说是从日本传过来的。
set特点:1.不同的元素组成。
2.无序
3.集合中的元素是不可变类型。.(int,str,tuple)
s= {11,"22",44,11} print(s)
11虽然设置了两次,输入结果只有1个11;第一个输出是“22”,而不是11,说明是无序的。
1.set(iterable)直接将括号内容(可迭代)转为集合
s1=set({"123":2}) s2=set("hello") print(s1,s2)
2.clear
s={1,2,"a"} s.clear() print(s)
3.copy
4.pop-随机删除一个元素
remove(value)删除指定元素,元素不存在报错
discard(value)直译为丢弃,元素不存在不会报错,do nothing
s={1,2,"a"} s.discard("b") print(s)
5.为什么有集合,比如
python_l=["lcg","szw","zjw"] linux_l=["lcg","szw","sb"]
求两个list共有元素,得用for循环来遍历,比较麻烦
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] python_l_and_linux_l = [] for i in python_l: if i in linux_l: python_l_and_linux_l.append(i) print(python_l_and_linux_l)
而用集合就很简单。求交集即可,用intersection/&
inter这个前缀的意思是,相互,互动,intersection直译就是互相选择,即交集
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.intersection(li_s))
&效果一样
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s&li_s)
6.并集union/|
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.union(li_s))
| 效果一样
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s|li_s)
7差集,A-B共同部分元素,A剩下的元素
difference,原集合不会更新
difference——update原集合会更新
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.difference(li_s))
print(py_s)
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) py_s.difference_update(li_s) print(py_s)
直接用减号,效果一样
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s-li_s)
8交叉补集(下图A+C)symmetric_difference。或用^
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.symmetric_difference(li_s))
9.isdisjoint:joint单词的意思是“共有的”,加上前缀就是“是否没有共有部分”,没有共有部分返回True
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.isdisjoint(li_s))
10.issubset:sub前缀的意思是“分支,亚种”,subset就是分支集合,就是子集的意思。判断是否是子集。
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.issubset(li_s))
11.issuperset:是否是父集
python_l = ["lcg", "szw", "zjw","sb"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) print(py_s.issuperset(li_s))
12.update(iterable)-更新集合,而add一次只能添加一个元素
python_l = ["lcg", "szw", "zjw"] linux_l = ["lcg", "szw", "sb"] py_s=set(python_l) li_s=set(linux_l) py_s.update(li_s) print(py_s)
13.frozenset-不可修改的set