【发布时间】:2011-08-05 09:19:22
【问题描述】:
我试图理解理解是如何工作的。
我想遍历两个列表,然后比较每个列表以找出差异。 如果一个/或多个单词不同,我想打印这个单词。
我希望这一切都在一行漂亮的代码中,这就是我对推导感兴趣的原因。
【问题讨论】:
标签: list python-3.x list-comprehension
我试图理解理解是如何工作的。
我想遍历两个列表,然后比较每个列表以找出差异。 如果一个/或多个单词不同,我想打印这个单词。
我希望这一切都在一行漂亮的代码中,这就是我对推导感兴趣的原因。
【问题讨论】:
标签: list python-3.x list-comprehension
在“一行漂亮的代码”中执行此操作是代码高尔夫,并且被误导了。改为可读。
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]
除了扩展版本比理解更容易阅读和理解。
【讨论】:
None 值的毫无意义的列表 - 这是不符合 Python 标准的,列表 Comphrensions 用于构建列表而不是过程调用
就像 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']
随着列表大小的增加,效率会大大降低。
【讨论】:
set 的使用不会产生正确的结果。