# Python3列表（list）比较操作教程

## 一、相等比较

### 1.1 同顺序列表比较

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

### 2.1 不同顺序列表进行比较

“==”只有成员、成员位置都相同时才返回True，但有时候我们希望只要成员相同、即使成员位置不同也能返回True。

### 2.1.1 使用列表sort()方法进行排序后比较

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

### 2.1.2 使用sorted()方法进行排序后比较

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

## 二、包含比较

### 2.1 判断列表是否包含另一列表

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

2.2 获取两个列表相同成员（交集）

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 获取一个列表中不是另一个列表成员的成员（差集）

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

2.5 获取两个列表所有成员（并集）

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

posted on 2019-01-16 11:43  诸子流  阅读(51947)  评论(1编辑  收藏  举报