简体   繁体   English

获得两个2D列表之间的差异

[英]Getting the different between two 2D lists

I have a 2D list of lists, I am doing some stuff to it and getting, as a result a slightly modified 2d lists of lists. 我有一个列表的2D列表,我正在做一些东西并获得,因此稍微修改了2d列表列表。 I cannot track what changes are being made until after I get the new list back. 在重新获取新列表之前,我无法跟踪正在进行的更改。 I want to get a list of all the items that have been changed such that [[1,2,3], [4,5,6], [7,8,9]] becomes [[1,None,3], [4,None,6], [7,None, None]] and I would get a list [(0,1), (1,1), (2, 1), (2,2)] I know you can normally do list(set(a)-set(b)) but when I tried it I got TypeError: unhashable type: 'list' So what is the most efficient way of doing this? 我想得到一个已经改变的所有项目的列表, [[1,2,3], [4,5,6], [7,8,9]]成为[[1,None,3], [4,None,6], [7,None, None]]我会得到一个列表[(0,1), (1,1), (2, 1), (2,2)]我知道你通常可以做list(set(a)-set(b))但是当我尝试它时我得到TypeError: unhashable type: 'list'那么最有效的方法是什么?

Using zip , enumerate and a generator function: 使用zipenumerate和生成器函数:

def diff(lis1, lis2):
    for i, (x, y) in enumerate(zip(lis1, lis2)):
        for j, (x1, y1) in enumerate(zip(x, y)):
            if x1 != y1:
                yield i, j
...                 
>>> lis1 = [[1,2,3], [4,5,6], [7,8,9]]
>>> lis2 = [[1,None,3], [4,None,6], [7,None, None]]
>>> list(diff(lis1, lis2))
[(0, 1), (1, 1), (2, 1), (2, 2)]

Using list comprehension: 使用列表理解:

>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> b = [[1,None,3], [4,None,6], [7,None, None]]
>>> [(i,j) for i, row in enumerate(a) for j, x in enumerate(row) if b[i][j] != x]
[(0, 1), (1, 1), (2, 1), (2, 2)]

If the lists have a regular structure, that is each of the sub-lists has the same length, and you don't mind using external packages, numpy can help. 如果列表具有常规结构,即每个子列表具有相同的长度,并且您不介意使用外部包, numpy可以提供帮助。

import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9]])
b = np.array([[1,None,3], [4,None,6], [7,None, None]])

print(np.where(a!=b))

>>>(array([0, 1, 2, 2]), array([1, 1, 1, 2]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM