rwrecougnrejwcgrthc
rwrecougnrejwcgrthc

Reputation: 37

How to compare exact list elements in 2 same length list?

Trying to compare the similarity of 2 lists, to see how many times the 2 lists match.

My code is this:

list1 = [1,0,1,0,1,1,0,0]
list2 = [1,0,0,1,0,0,1,1]

def listCompare(lst1, lst2):
    for i in lst1:
        for j in lst2:
            if i == j:
                return i

print(listCompare(L1, M1))

This should return 2, because only the first and second item (index 0 and 1) are equal in both lists.

Upvotes: 1

Views: 1363

Answers (4)

fthkrn
fthkrn

Reputation: 11

def listCompare(lst1, lst2):
    for i in lst1:
        for j in lst2:
            if i == j:
                return i

Your code compare each item in list1 to all item in list2. You can use this code.

list1 = [1,0,1,0,1,1,0,0]
list2 = [1,0,0,1,0,0,1,1]

def listCompare(lst1, lst2):
    i=0
    counter=0
    for j in lst1:
        if lst1[i]==lst2[i]:
            counter+=1
            i+=1
        else:
            i+=1
    return counter

print(listCompare(list1,list2))

Upvotes: 0

SparkAndShine
SparkAndShine

Reputation: 18007

How about this,

list1 = [1,0,1,0,1,1,0,0]
list2 = [1,0,0,1,0,0,1,1]

n = sum(i==j for i, j in zip(list1, list2))

print(n)
# 2

Upvotes: 1

kjmerf
kjmerf

Reputation: 4335

I think you just want:

list1 = [1,0,1,0,1,1,0,0]
list2 = [1,0,0,1,0,0,1,1]

def listCompare(lst1, lst2):
    matches = 0
    for i in range(0, len(lst1)):
        if lst1[i] == lst2[i]:
            matches += 1
    return matches

print(listCompare(list1, list2))

That is, just use one index to loop through both lists, and create a variable called matches to count the number of matches you find.

Upvotes: 1

MSeifert
MSeifert

Reputation: 152637

You could map operator.eq on both lists and then sum them:

>>> import operator
>>> sum(map(operator.eq, list1, list2))
2

You compared the cartesian-product (each item of list1 with each item of list2) not the element-wise equality.

Upvotes: 3

Related Questions