Count the identical pairs in two lists
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]
In a one-liner:
sum(x == y for x, y in zip(a, b))
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
and1
- add up the
1
s withsum()