簡體   English   中英

比較 Python 中的兩個列表列表,找出具有相同索引的列表之間的差異

[英]Compare two lists of lists in Python and find the difference between lists with the same indices

例如,如果我們有

ListofLists1 = [[0], [0], [1, 3], [1, 4], []] 

ListofLists2 = [[0, 2], [0, 1, 2, 3], [1, 3, 4], [1, 3, 4], [0, 1, 3]] 

我們定義

Diff = ListofLists2 - ListofLists1

我想要以下形式的輸出

Diff = [[2], [1,2,3], [4], [3], [0,1,3]]

對於我正在做的特定類型的工作,我總是希望在 ListofLists2 中相應(相同索引)列表中包含的 ListofLists1 內的任何列表中找到所有元素。 但是,ListofLists2 中的列表可能包含 ListofLists1 中相應列表中不存在的元素。

將兩個列表壓縮在一起,作為列表理解的一部分遍歷它們,並在每種情況下找到集合對稱差異,將每個結果集設置為列表類型:

ListofLists1 = [[0], [0], [1, 3], [1, 4], []] 
ListofLists2 = [[0, 2], [0, 1, 2, 3], [1, 3, 4], [1, 3, 4], [0, 1, 3]]

[list(set(l1).symmetric_difference(l2)) for l1,l2 in zip(ListofLists1,ListofLists2)]

給出:

[[2], [1, 2, 3], [4], [3], [0, 1, 3]]

另一個解決方案剛剛擊中了我的大腦。 關於什么

Diff = map( lambda x,y: list(set(x) - set(y)), ListofLists2, ListofLists1 )

這也返回

Diff = [[2], [1,2,3], [4], [3], [0,1,3]]

為了

ListofLists1 = [[0], [0], [1, 3], [1, 4], []] 
ListofLists2 = [[0, 2], [0, 1, 2, 3], [1, 3, 4], [1, 3, 4], [0, 1, 3]]  

關於這種方法如何與psychemedia的答案進行比較的任何想法(就通常長度為數千萬的列表的實施速度而言)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM