gpt4 book ai didi

python - 如何比较两个列表并返回它们在 python 中每个索引处匹配的次数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:56 27 4
gpt4 key购买 nike

我有两个包含 1 和 0 的列表,例如

list1 = [1,1,0,1,0,1]
list2 = [0,1,0,1,1,0]

我想找到它们在每个索引处匹配的次数。所以在这种情况下,输出将为 3,因为它们仅在索引 1,2 和 3 处具有相同的值。

目前我正在这样做:

matches_list = []
for i in list1:
index = list[1].index(i)
if list1[index] == list2[index]:
mathes_list.append(i)
else:
pass
return len(matches_list)

但是这很慢,我想重复多次以比较大量这些列表

我希望有人可以建议我以更快的方式执行此操作。有没有办法使用 set() 函数或类似的东西,例如比较两个列表但保持每个列表的顺序?

最佳答案

zip 列表,比较元素,计算总和。

>>> list1 = [1,1,0,1,0,1]
>>> list2 = [0,1,0,1,1,0]
>>> sum(a == b for a,b in zip(list1, list2))
3

(考虑在 Python 2 中使用 itertools.izip 以提高内存效率。)

关于python - 如何比较两个列表并返回它们在 python 中每个索引处匹配的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43327960/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com