我試圖理解如何理解工作。Python - 在理解中比較兩個列表
我想遍歷兩個列表,並比較每個找出差異。 如果有一個或多個單詞不同,我希望打印這個單詞。
我想這一切都在一個很好的代碼行,這就是爲什麼我對理解感興趣。
我試圖理解如何理解工作。Python - 在理解中比較兩個列表
我想遍歷兩個列表,並比較每個找出差異。 如果有一個或多個單詞不同,我希望打印這個單詞。
我想這一切都在一個很好的代碼行,這就是爲什麼我對理解感興趣。
像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')
如果你想比較兩個列表的差異,我想你想使用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']
更高效爲列表的大小增長。
在「一行不錯的代碼」中這樣做是代碼高爾夫,並且被誤導了。改爲可讀。
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]
除了擴展版本更容易閱讀和理解比的理解。
感謝您的回答:)) – Rhys 2011-04-14 10:37:30