Python-比较理解中的两个列表 [英] Python - Compare two lists in a comprehension

查看:59
本文介绍了Python-比较理解中的两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解理解的原理.

I'm trying to understand how comprehensions work.

我想遍历两个列表,并比较每个列表以发现差异. 如果一个或多个单词不同,我想打印这个单词.

I would like to loop through two lists, and compare each to find differences. If one/or-more word(s) is different, I would like to print this word(s).

我希望在一个不错的代码行中做到这一点,这就是为什么我对理解力很感兴趣.

推荐答案

像kriegar建议使用集合可能是最简单的解决方案.如果您绝对需要使用列表理解功能,则可以使用类似以下的方法:

Like kriegar suggested using sets is probably the easiest solution. If you absolutely need to use list comprehension, I'd use something like this:

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')

这篇关于Python-比较理解中的两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆