I have two lists of the same length, and I want to count the number of positions in which the elements of both lists match. I've done something like this but I think it doesn't make much sense:
def cuenta_coincidentes(l1,l2):
res=0;
for x in l1:
for y in l2:
if l1.index(x)==l2.index(y):
res+=1;
return res;
A very simple way is the following:
Being sure that both lists have the same length, we can:
zip(lista1, lista2)
we combine each element of the two lists into tuples, that is, like this:(1,1), (4,2), (5,5), (6,8), (3,3)
a == b
, theTrue
is coerced to 1, so the sum will give us the number of matching elements.To know how many times it happens that the element of list1 in position x is equal to the element of list2 in the same position x, then all you have to do is go through both lists at the same time and compare that element.