2011-04-14 48 views
3

我試圖理解如何理解工作。Python - 在理解中比較兩個列表

我想遍歷兩個列表,並比較每個找出差異。 如果有一個或多個單詞不同,我希望打印這個單詞。

我想這一切都在一個很好的代碼行,這就是爲什麼我對理解感興趣。

回答

7

像kriegar建議使用套件可能是最簡單的解決方案。如果你絕對需要使用列表理解,我會使用這樣的事情:

list_1 = [1, 2, 3, 4, 5, 6] 
list_2 = [1, 2, 3, 0, 5, 6] 

# Print all items from list_1 that are not in list_2() 
print(*[item for item in list_1 if item not in list_2], sep='\n') 

# Print all items from list_1 that differ from the item at the same index in list_2 
print(*[x for x, y in zip(list_1, list_2) if x != y], sep='\n') 

# Print all items from list_2 that differ from the item at the same index in list_1 
print(*[y for x, y in zip(list_1, list_2) if x != y], sep='\n') 
+0

感謝您的回答:)) – Rhys 2011-04-14 10:37:30

2

如果你想比較兩個列表的差異,我想你想使用set

s.symmetric_difference(t) s^t new set with elements in either s or t but not both 

例如:

>>> L1 = ['a', 'b', 'c', 'd'] 
>>> L2 = ['b', 'c', 'd', 'e'] 
>>> S1 = set(L1) 
>>> S2 = set(L2) 
>>> difference = list(S1.symmetric_difference(S2)) 
>>> print difference 
['a', 'e'] 
>>> 

單行形式?

>>> print list(set(L1).symmetric_difference(set(L2))) 
['a', 'e'] 
>>> 

,如果你真的想用一個列表理解:

>>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1] 
['a', 'e'] 

更高效爲列表的大小增長。

+0

這是一個很好的建議,我會挑釁地使用它。但在我追求更多關於理解的追求中,我總是給überjesus一點點勾號......除非我可以給予超過一個,沒有嘗試過 – Rhys 2011-04-14 10:35:28

+0

我的理解是元素可以重複,順序也很重要。這樣'set'的使用不會產生正確的結果。 – pepr 2012-07-18 21:18:47

10

在「一行不錯的代碼」中這樣做是代碼高爾夫,並且被誤導了。改爲可讀。

for a, b in zip(list1, list2): 
    if a != b: 
     print(a, "is different from", b) 

這不是在任何與此顯著方式不同:

[print(a, "is different from", b) for a, b in zip(list1, list2) if a!=b] 

除了擴展版本更容易閱讀和理解比的理解。

+0

我同意,它更容易閱讀,但我一直這樣做了一段時間,我的gettig無聊了..不是拉鍊方法壽,謝謝你給我看。如果這些方法更短...我可能aswel瞭解它...可能會派上用場 – Rhys 2011-04-14 10:31:29

+2

不,沒有更簡單的方法來做這種比較。其他解決方案對「差異」有不同的看法。哪個是對的取決於你。厭倦編寫好的代碼可能不是一個好的理由。 ;) – 2011-04-14 11:25:01

+2

得說這是一些強大的罰款代碼高爾夫 – Rhys 2011-04-16 14:05:58