2013-09-29 101 views
2

我有一個列表的二維列表,我正在做一些東西,並得到,因此略有修改列表的二維列表。我無法跟蹤在我收到新列表之前要進行的更改。我想獲得所有已更改的項目列表,其中 [[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'那麼什麼是最有效的方法這樣做?獲取兩個2D列表之間的差異

回答

3

使用列表理解:

>>> 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)] 
4

使用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)] 
0

如果列表中有一個規則的結構,即每個子列表具有相同的長度,你不介意使用外部軟件包,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])) 
相關問題