问题描述
在 Python 2.7 中,我有两个整数列表:
x = [1, 3, 2, 0, 2]y = [1, 2, 2, 3, 1]
我想创建第三个列表,指示 x
和 y
中的每个元素是否相同,以产生:
z = [1, 0, 1, 0, 0]
我如何使用列表理解来做到这一点?
我的尝试是:
z = [i == j for i,j in ...]
但我不知道如何完成它.
您正在寻找 zip
z = [i == j for i,j in zip(x,y)]
但你最好添加 int
调用以获得所需的输出
否则你会得到一个列表,如 [True, False, True, False, False]
正如 ajcr 在 注释,如果列表很长,最好使用 itertools.izip 而不是 zip.这是因为它返回一个迭代器而不是一个列表.文档
中提到了这一点与 zip() 类似,但它返回一个迭代器而不是一个列表.
演示
>>>从 itertools 导入 izip>>>z = [int(i == j) for i,j in izip(x,y)]>>>z[1, 0, 1, 0, 0]In Python 2.7, I have two lists of integers:
x = [1, 3, 2, 0, 2]
y = [1, 2, 2, 3, 1]
I want to create a third list which indicates whether each element in x
and y
is identical, to yield:
z = [1, 0, 1, 0, 0]
How can I do this using list comprehension?
My attempt is:
z = [i == j for i,j in ...]
But I don't know how to complete it.
You are looking for zip
z = [i == j for i,j in zip(x,y)]
But you better add int
call to get your desired output
>>> z = [int(i == j) for i,j in zip(x,y)]
>>> z
[1, 0, 1, 0, 0]
else you'll get a list like [True, False, True, False, False]
As ajcr mentions in a comment, it is better to use itertools.izip instead of zip if the lists are very long. This is because it returns an iterator instead of a list. This is mentioned in the documentation
demo
>>> from itertools import izip
>>> z = [int(i == j) for i,j in izip(x,y)]
>>> z
[1, 0, 1, 0, 0]
这篇关于比较 Python 中两个列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!