Krush23
Krush23

Reputation: 741

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)

Upvotes: 15

Views: 5361

Answers (6)

U13-Forward
U13-Forward

Reputation: 71580

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

Upvotes: 0

Ardweaden
Ardweaden

Reputation: 887

Using numpy:

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

Upvotes: 1

yatu
yatu

Reputation: 88246

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]

Upvotes: 15

Deepstop
Deepstop

Reputation: 3807

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

Upvotes: 1

Klaus D.
Klaus D.

Reputation: 14369

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 1s with sum()

Upvotes: 7

martyn
martyn

Reputation: 716

In a one-liner:

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

Upvotes: 35

Related Questions