2011-04-14 50 views
3

我试图理解如何理解工作。Python - 在理解中比较两个列表

我想遍历两个列表,并比较每个找出差异。 如果有一个或多个单词不同,我希望打印这个单词。

我想这一切都在一个很好的代码行,这就是为什么我对理解感兴趣。

回答

7

像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') 
+0

感谢您的回答:)) – Rhys 2011-04-14 10:37:30

2

如果你想比较两个列表的差异,我想你想使用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'] 

更高效为列表的大小增长。

+0

这是一个很好的建议,我会挑衅地使用它。但在我追求更多关于理解的追求中,我总是给überjesus一点点勾号......除非我可以给予超过一个,没有尝试过 – Rhys 2011-04-14 10:35:28

+0

我的理解是元素可以重复,顺序也很重要。这样'set'的使用不会产生正确的结果。 – pepr 2012-07-18 21:18:47

10

在“一行不错的代码”中这样做是代码高尔夫,并且被误导了。改为可读。

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] 

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

+0

我同意,它更容易阅读,但我一直这样做了一段时间,我的gettig无聊了..不是拉链方法寿,谢谢你给我看。如果这些方法更短...我可能aswel了解它...可能会派上用场 – Rhys 2011-04-14 10:31:29

+2

不,没有更简单的方法来做这种比较。其他解决方案对“差异”有不同的看法。哪个是对的取决于你。厌倦编写好的代码可能不是一个好的理由。 ;) – 2011-04-14 11:25:01

+2

得说这是一些强大的罚款代码高尔夫 – Rhys 2011-04-16 14:05:58