How To Compare Two Lists And Return The Number Of Times They Match At Each Index In Python?
I have two lists containing 1's and 0's, e.g. list1 = [1,1,0,1,0,1] list2 = [0,1,0,1,1,0] I want to find the number of times they match at each index. So in this case the output w
Solution 1:
zip
the lists, compare the elements, compute the sum.
>>>list1 = [1,1,0,1,0,1]>>>list2 = [0,1,0,1,1,0]>>>sum(a == b for a,b inzip(list1, list2))
3
(Consider using itertools.izip
in Python 2 for memory efficiency.)
Solution 2:
Here's a lightning fast numpy answer:
import numpy as np
list1 = np.array([1,1,0,1,0,1])
list2 = np.array([0,1,0,1,1,0])
len(np.where(list1==list2)[0])
The numpy np.where
function will return the indexes of all the points in the pair of lists that conform to a function (in this case list1==list2 at indices [1,2,3]) along with a datatype description. In the above case, I strip out the array of indices and count how many there are with len()
.
Solution 3:
You can use map
with operator.eq
and sum
:
>>>import operator>>>sum(map(operator.eq, list1, list2))
This works because True
is interpreted as 1 when summed and False
like 0
.
You could also use numpy
for this:
>>>import numpy as np>>>np.count_nonzero(np.asarray(list1) == np.asarray(list2))
Post a Comment for "How To Compare Two Lists And Return The Number Of Times They Match At Each Index In Python?"