中两个列表中的值

中两个列表中的值

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

问题描述

在 Python 2.7 中,我有两个整数列表:

x = [1, 3, 2, 0, 2]y = [1, 2, 2, 3, 1]

我想创建第三个列表,指示 xy 中的每个元素是否相同,以产生:

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 调用以获得所需的输出

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

demo

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

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

08-05 21:56