Python - 在理解中比较两个列表

Rhy*_*hys 4 list-comprehension list python-3.x

我试图理解理解是如何运作的.

我想循环遍历两个列表,并比较每个列表以找出差异.如果一个/多个单词不同,我想打印这个单词.

我喜欢这一切的代码,这就是为什么我对理解感兴趣.

Len*_*bro 12

在"一个很好的代码行"中执行它是代码高尔夫,并且被误导.让它变得可读.

for a, b in zip(list1, list2):
    if a != b:
       print(a, "is different from", b) 
Run Code Online (Sandbox Code Playgroud)

这在任何重要方面都没有区别:

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

除了扩展版本比理解更容易阅读和理解.

  • 不,没有更短的方法来进行这种比较.其他解决方案对"差异"的看法有不同的看法.哪个是对的取决于你.厌倦了编写好的代码可能不是一个好理由.;) (2认同)
  • 必须说这是一些强大的优质代码高尔夫球 (2认同)

übe*_*sus 10

像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')
Run Code Online (Sandbox Code Playgroud)


DTi*_*ing 5

如果您想比较两个列表的差异,我认为您想使用set.

s.symmetric_difference(t)   s ^ t   new set with elements in either s or t but not both
Run Code Online (Sandbox Code Playgroud)

例子:

>>> 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']
>>> 
Run Code Online (Sandbox Code Playgroud)

一行形式?

>>> print list(set(L1).symmetric_difference(set(L2)))
['a', 'e']
>>> 
Run Code Online (Sandbox Code Playgroud)

如果你真的想使用列表理解:

>>> [word for word in L1 if word not in L2] + [word for word in L2 if word not in L1]
['a', 'e']
Run Code Online (Sandbox Code Playgroud)

随着列表大小的增长,效率会大大降低。