1. 程式人生 > 實用技巧 >python基礎-集合set的常用方法

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