简体   繁体   中英

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

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:

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:

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

You can use some of Python's special features:

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

This will

  • pair the list items with 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
  • add up the 1 s with sum()

Using a generator expression, take advantage of A == A is equal to 1 and A != A is equal to zero.

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:

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

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

Output:

6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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