顺序相同直接用“==”进行比较便可html
list1 = ["one","two","three"] list2 = ["one","two","three"] list1 == list2
“==”只有成员、成员位置都相同时才返回True,但有时候咱们但愿只要成员相同、即便成员位置不一样也能返回True。python
列表自己有sort()内置方法,可对自身成员进行排序;注意sort()方法对自身形成改变。spa
list1 = ["one","two","three"] list2 = ["one","three","two"] list1.sort() == list2.sort() print(list1)
上一小节介绍的sort()方法会对列表成员进行重排,但有时候咱们并不但愿列表自己被改动。3d
咱们能够用一下变量将原先的列表保存起来,但更好的作法是使用sorted()方法,sorted()不改变列表本来顺序而是新生成一个排序后的列表并返回。code
list1 = ["one","two","three"] list2 = ["one","three","two"] sorted(list1) == sorted(list2) print(list1) sorted(list1)
直接用列表自己进行包含类比较,只能用遍历的方法这是比较麻烦的,使用set()转成集合进行包含比较就简单多了。htm
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