如何比较两个列表并返回它们在python中每个索引处匹配的次数? [英] How to compare two lists and return the number of times they match at each index in python?

查看:103
本文介绍了如何比较两个列表并返回它们在python中每个索引处匹配的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two lists containing 1's and 0's, e.g.

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

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

I want to find the number of times they match at each index. So in this case the output would be 3 because they have the same value at indices 1,2 and 3 only.

目前我正在这样做:

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)

但是,这非常慢,我想反复进行多次以比较大量这些列表

However this is very slow and I want to do this many times over to compare a large number of these lists

我希望有人可以以更快的方式为我提供建议.有没有办法使用set()函数或类似的方法,例如比较两个列表,但保持每个列表的顺序?

I was hoping someone could advise me on a quicker way to do this. Is there a way to use the set() function, or something similar, for example to compare two lists but maintain the order of each one?

推荐答案

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

zip the lists, compare the elements, compute the sum.

>>> 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来提高内存效率.)

(Consider using itertools.izip in Python 2 for memory efficiency.)

这篇关于如何比较两个列表并返回它们在python中每个索引处匹配的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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