比较 2 个列表中的相同索引 [英] Comparing same index in 2 lists

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

问题描述

我没有这方面的代码,因为我不知道该怎么做,并且在 Google 上找不到太多帮助.

I don't have a code for this because I have no idea how to do it, and couldn't find much help on Google.

有没有办法找出 2 个列表上的相同索引是否相同?

Is there a way to find if the same indexes on 2 lists are the same?

例如:

x_list = [1, 2, 3, 4, 5]
y_list = [1, 2, A, B, 5]

我想知道 X 的第一个索引是否与 Y 的第一个索引相同,X 的第二个索引是否与 Y 的第二个索引相同,等等.我可以这样做:

I want to know whether the first index of X is the same as the first index of Y, the second index of X is the same as the second index of Y, etc. I could do it like:

x_list[0] == y_list[0]

但需要一个无限的解决方案.

But need an infinite solution.

推荐答案

zip 列表并返回测试(返回一个布尔值作为结果):

zip the lists and return the test (which returns a boolean as outcome):

[i == j for i, j in zip(x_list, y_list)]

如果您不需要这些值,您可以使用 any 快速检查是否存在 False(意味着项目不相同):

You could use any to quickly check for the existence of a False (means the items are not the same) if you don't need the values:

any(i != j for i, j in zip(x_list, y_list))

一旦发现 Falseany 版本就会中断,这意味着除了最坏的情况外,您可能不必遍历整个列表.

The any version would break once a False is found meaning you may not have to traverse the whole lists except in the worst case.

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

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