Python3列表(list)比較操做教程

1、相等比較

1.1 同順序列表比較

順序相同直接用「==」進行比較便可html

list1 = ["one","two","three"]
list2 = ["one","two","three"]
list1 == list2

 

2.1 不一樣順序列表進行比較

「==」只有成員、成員位置都相同時才返回True,但有時候咱們但願只要成員相同、即便成員位置不一樣也能返回True。python

 

2.1.1 使用列表sort()方法進行排序後比較

列表自己有sort()內置方法,可對自身成員進行排序;注意sort()方法對自身形成改變。spa

list1 = ["one","two","three"]
list2 = ["one","three","two"]
list1.sort() == list2.sort()
print(list1)

 

2.1.2 使用sorted()方法進行排序後比較

上一小節介紹的sort()方法會對列表成員進行重排,但有時候咱們並不但願列表自己被改動。3d

咱們能夠用一下變量將原先的列表保存起來,但更好的作法是使用sorted()方法,sorted()不改變列表本來順序而是新生成一個排序後的列表並返回。code

list1 = ["one","two","three"]
list2 = ["one","three","two"]
sorted(list1) == sorted(list2)
print(list1)
sorted(list1)

 

2、包含比較

直接用列表自己進行包含類比較,只能用遍歷的方法這是比較麻煩的,使用set()轉成集合進行包含比較就簡單多了。htm

 

2.1 判斷列表是否包含另外一列表

list1 = ["one","two","three"]
list2 = ["one","three","two","four"]
set(list1).issubset(set(list2))
set(list2).issuperset(set(list1))

 

2.2 獲取兩個列表相同成員(交集)blog

list1 = ["one","two","three","five"]
list2 = ["one","three","two","four"]
set(list1).intersection(set(list2))

 

2.3 獲取兩個列表不一樣成員排序

list1 = ["one","two","three","five"]
list2 = ["one","three","two","four"]
set(list1).symmetric_difference(set(list2))

 

2.4 獲取一個列表中不是另外一個列表成員的成員(差集)three

list1 = ["one","two","three","five"]
list2 = ["one","three","two","four"]
set(list1).difference(set(list2))
set(list2).difference(set(list1))

 

2.5 獲取兩個列表全部成員(並集)get

list1 = ["one","two","three","five"]
list2 = ["one","three","two","four"]
set(list1).union(set(list2))

 

參考:

https://stackoverflow.com/questions/9623114/check-if-two-unordered-lists-are-equal

https://stackoverflow.com/questions/3847386/testing-if-a-list-contains-another-list-with-python

http://www.runoob.com/python3/python3-set.html

相關文章
相關標籤/搜索