我试图理解如何理解工作。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