2017-01-06 115 views
-3

我列出的兩個列表:如何從一個列表中刪除不包含在另一個列表中的元素?

arr1 = [[1,2,3], 
     [2,5,1,1], 
     [3,1,1]] 

arr2 = [[2,3,6,1], 
     [8,1,3], 
     [5,5,6]] 

我需要檢查從ARR2元素不包含在ARR1和刪除ARR2這些元素。

那麼結果必然是:

arr2 = [[2,3,1], 
     [1,3], 
     [5,5]] 

6,8不包含在ARR1,所以它在ARR2刪除。

如何做到這一點?

+0

嘗試搜索 「名單交集」 - E,G,http://stackoverflow.com/questions/642763/python-intersection-of-two-lists – DNA

+0

連'7'不在'arr1'中,它是如何出現在'arr2'中的?請[編輯]你的文章並添加[mcve]。見[問]。 –

回答

1
arr1 = [[1, 2, 3], 
     [2, 5, 1, 1], 
     [3, 1, 1]] 

arr2 = [[2, 3, 6, 1], 
     [8, 1, 3], 
     [7, 5, 6]] 

set1 = set(sum(arr1, [])) 
print('Elements found in arr1:') 
print(set1) 

arr3 = [[x for x in sub if x in set1] 
     for sub in arr2] 

print('Sublists of arr3:') 
for sub in arr3: 
    print(sub) 

輸出:

Elements found in arr1: 
set([1, 2, 3, 5]) 
Sublists of arr3: 
[2, 3, 1] 
[1, 3] 
[5] 
相關問題