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)
.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With