简体   繁体   English

计算两个列表中的相同对

[英]Count the identical pairs in two lists

My list has 我的清单有

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]

I need to count if a[i]==b[i] . 我需要算一下a[i]==b[i]

For the above example, the answer should be 对于上面的例子,答案应该是

6

Detail description of answer is 答案的详细描述是

a[0]==b[0] (1==1)
a[1]==b[1] (2==2)
a[2]==b[0] (3==3)
a[4]==b[4] (2==2)
a[8]==b[8] (6==6)
a[9]==b[9] (7==7)

在单行中:

sum(x == y for x, y in zip(a, b))

One way would be to map both lists with operator.eq and take the sum of the result: 一种方法是使用operator.eq map两个列表并获取结果的sum

from operator import eq

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]

sum(map(eq, a, b))
# 6

Where by mapping the eq operator we get either True or False depending on whether items with the same index are the same: 通过映射eq运算符,我们得到TrueFalse具体取决于具有相同索引的项是否相同:

list(map(eq, a, b))
# [True, True, True, False, True, False, False, False, True, True]

You can use some of Python's special features: 您可以使用Python的一些特殊功能:

sum(i1 == i2 for i1, i2 in zip(a, b))

This will 这将

  • pair the list items with zip() zip()配对列表项
  • use a generator expression to iterate over the paired items 使用生成器表达式迭代配对的项目
  • expand the item pairs into two variables 将项目对扩展为两个变量
  • compare the variables, which results in a boolean that is also usable as 0 and 1 比较变量,得到一个也可用作01的布尔值
  • add up the 1 s with sum() sum()1

Using a generator expression, take advantage of A == A is equal to 1 and A != A is equal to zero. 使用生成器表达式,利用A == A等于1, A != A等于零。

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]
count = sum(a[i] == b[i] for i in range(len(a)))
print(count)

6

Using numpy: 使用numpy:

import numpy as np
np.sum(np.array(a) == np.array(b))

A little similar to @yatu's solution, but I save an import, I use int.__eq__ : 有点类似于@ yatu的解决方案,但我保存导入,我使用int.__eq__

print(sum(map(int.__eq__, a, b)))

Output: 输出:

6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM