Cruvey
Cruvey

Reputation: 35

How do I count how many times element in a list are an exact match of another list - python

I have two lists and want a count of how many times elements in a list are an exact match and are in the same position as another list. So for example:

list1 = [1,2,3,4]
list2 = [1,2,4,3]

would return 2. I have the following code:

count = 0
def corrpos(list1, list2, count):
    if list1[0] == list2[0]:
            count = 1
    return count

this works to compare the first element, but I am unsure how to make it keep track for all the elements. Any tips?

Upvotes: 1

Views: 793

Answers (3)

mgc
mgc

Reputation: 5443

For the sake of completeness I will propose an answer using the built-in zip, so the last answer provided by @LMc could be rewritten as :

def corrpos(list1, list2):
    count = 0
    for elem1, elem2 in zip(list1, list2):
        if elem1 == elem2:
            count += 1
    return count

It didn't really provide something more, but zip allow you to iterate "in the same time" on two iterables and I guess this method is more intuitive than having to use the index of the elements from the first list to select those from the second list as in the example with enumerate.

Of course it can also be rewritten to be a oneliner as in the other answers :

def corrpos(list1, list2):
    return sum(1 for elem1, elem2 in zip(list1, list2) if elem1 == elem2)

or

def corrpos(list1, list2):
    return len([True for elem1, elem2 in zip(list1, list2) if elem1 == elem2])

Upvotes: 1

LMc
LMc

Reputation: 18642

Another way you could do this is see the intersection of these two lists using sets:

>>>set(list1) & set(list2)
set([1, 2, 3, 4])

Then you can just use the len function to get a count:

>>>len(set(list1) & set(list2))
4

Update:

Given that the elements have to be in the same index location, I would use a list comprehension:

def corrpos(list1,list2):
    return len([i for (c,i) in enumerate(list1) if list2[c]==i])

Here the enumerate function keeps track of the index location as you loop through list1 and can be used to look up the corresponding value in list2.

If you want to use a for loop, this can be rewritten as:

def corrpos(list1,list2):
    count=0
    for (c,i) in enumerate(list1):
        if list2[c]==i: count+=1
    return count

Upvotes: 0

petruz
petruz

Reputation: 535

You can make a list comprehension and calculate the number of elements of list1 that were present in list2 by using len():

print len([x for x in list1 if x in list2])

Your own code is also working, you would just have to return count (and change the input of the parameter correctly to list2):

return count

Upvotes: 1

Related Questions