-1

I want to take two lists and want to count the values that appear in both but considering the same position.

a = [1, 2, 3, 4, 5]
b = [4, 5, 3, 6, 5]

returnMatches(a, b)

would return 2, for instance.

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 3, 5]

returnMatches(a, b)

would return 4, for instance.

Is there a pythonic one line option or do I really need to iterate over both lists?

Thanks

Jürgen K.
  • 3,427
  • 9
  • 30
  • 66

3 Answers3

2

Try

output = sum([x == y for x, y in zip(a, b)])

I am not sure if it needs further clarification. You might want to look into "list comprehension" and zip() if you are not familiar with them.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
2

Look up what zip is and how list comprehension and generator expressions work:

def count_matches(a, b):
  return sum(x == y for x, y in zip(a, b))
Faboor
  • 1,365
  • 2
  • 10
  • 23
1
returnMatches = lambda a,b:sum([x==y for x,y in zip(a,b)]

This is the same as:

def returnMatches(a, b):
    matches = 0
    for x, y in zip(a, b):
        matches += 1
    return matches

Take a look at zip() for more information on that builtin

12944qwerty
  • 2,001
  • 1
  • 10
  • 30