Reputation: 741
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
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
Reputation: 887
Using numpy:
import numpy as np
np.sum(np.array(a) == np.array(b))
Upvotes: 1
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
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
Reputation: 14369
You can use some of Python's special features:
sum(i1 == i2 for i1, i2 in zip(a, b))
This will
zip()
0
and 1
1
s with sum()
Upvotes: 7