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\')
    
用“一条漂亮的代码行”来完成代码就是代码高尔夫,而且被误导了。使其更具可读性。
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]
除了扩展版本比理解版本更易于阅读和理解。     
如果您想比较两个列表的差异,我想您要使用
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\']
随着列表大小的增加,效率将大大降低。     

要回复问题请先登录注册