Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare each item of two lists in Python

Tags:

python

For example, suppose list_1 = [a,b,c] and list_2 = [m,n,o]. I want to compare each item from one list to the other, for example, create an output list such that

[a == m, a == n, a == o, b == m, b == n, b == o...]

For simplicity I'm using the == operation but this could also be a summation, e.g.

[a + m, a + n, a + o, b + m...]

I know how I could do this with two loops, but I'm wondering a lambda function with map() or list comprehensions could be used? I've searched online but only found one-to-one comparisons of list items, e.g. map(lambda x,y: x + y, list_1, list_2).

like image 297
Hamman Samuel Avatar asked Jul 03 '15 11:07

Hamman Samuel


2 Answers

itertools.product() can generate all combinations for you:

import itertools
list_1 = [1,5,4]
list_2 = [2,3,4]
# using list comprehensions
comparisons = [a == b for (a, b) in itertools.product(list_1, list_2)]
sums = [a + b for (a, b) in itertools.product(list_1, list_2)]
# using map and lambda
comparisons = map(lambda (a, b): a == b, itertools.product(list_1, list_2))
sums = map(lambda (a, b): a + b, itertools.product(list_1, list_2))
like image 111
Roel Schroeven Avatar answered Oct 01 '22 18:10

Roel Schroeven


To get all the permutations of elements with a list comprehension:

[a == b for a in list_1 for b in list_2]

Functionality is the same as the nested for loops:

list_3 = []
for a in list_1:
    for b in list_2:
        list_3.append(a == b)  # Or a + b, etc.

Functional implementation is a bit more confusing:

list_3 = map(lambda x: map(lambda y: y == x, list_2), list_1)

This creates a list of lists, however, so you'd want to flatten it with any of the techniques described here

sum(list_3, [])

Or use itertools.product as suggested by @bereal.

like image 31
jayelm Avatar answered Oct 01 '22 19:10

jayelm