如何在Python 3中列出两个嵌套列表之间的区别?

时间:2018-04-29 22:11:12

标签: python python-3.x list

我有两个这样的嵌套列表:

list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]
list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]]

我想列出两个嵌套列表中的不同值,如下所示:

[5,8,8,9,4,7]

Python 3中有没有办法做到这一点?

这就是我的尝试:

list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]
list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]]
storer = []
for x in list_2:
    if x not in list_1:
       storer.append(x)
print(storer)

但它返回:

[[8, 3, 4], [1, 5, 9], [6, 7, 2]]

3 个答案:

答案 0 :(得分:1)

使用set差异的另一种方法:

final = sum((list(set(k) - set(v)) + list(set(v) - set(k)) for k, v in zip(list_1, list_2)), [])
# [5, 8, 8, 9, 4, 7]

使用reduce的结果相同:

from functools import reduce

final = reduce(list.__iadd__, (list(set(k) - set(v)) + list(set(v) - set(k)) for k, v in zip(list_1, list_2)))
# [5, 8, 8, 9, 4, 7]

答案 1 :(得分:0)

#!/usr/bin/env python

list_1 = [[5, 3, 4], [1, 5, 8], [6, 4, 2]]
list_2 = [[8, 3, 4], [1, 5, 9], [6, 7, 2]]

difflist = [a[i][j] for a in zip(list_1, list_2) for i in range(len(a)) for j in range(len(a[i])) if a[i][j] != a[i-1][j]]
print(difflist)

打印哪些:

[5,8,8,9,4,7]

答案 2 :(得分:0)

稍后回答,但您可以使用set(list_1[i]) ^ set(list_2[i]),即:

final = []
for i in range(len(list_1)):
    [final.append(x) for x in reversed([y for y in set(list_1[i]) ^ set(list_2[i])])]
# [5, 8, 9, 8, 7, 4]

Demo