且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较 Python 中两个列表中的值

更新时间:2022-11-17 17:40:40

您正在寻找 zip

z = [i == j for i,j in zip(x,y)]

但你***添加 int 调用以获得所需的输出

>>>z = [int(i == j) for i,j in zip(x,y)]>>>z[1, 0, 1, 0, 0]

否则你会得到一个列表,如 [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

Like zip() except that it returns an iterator instead of a list.

demo

>>> from itertools import izip
>>> z = [int(i == j) for i,j in izip(x,y)]
>>> z
[1, 0, 1, 0, 0]