Search code examples
pythonpython-itertools

Minimum of itertools.product in python


import itertools

A = [50, 60, 70]
B = [0.3, 0.1, 0.5, 0.4]

print [a + b for a, b in itertools.product(A, B)]

>> [50.3,50.1,50.5,50.4,60.3,60.1,60.5,60.4,70.3,70.1,70.5,70.4]

In the above code, is there a way to just return the minimum value of a + b for each a? so the output should be:

[50.1,60.1,70.1]

please note this is a toy example, in the real example A and B are lists of lat and lon values and I compute the great circle distance between them


Solution

  • itertools.product isn't really appropriate for your Great Circle task because it lumps all the (A, B) pairs into one container, but you want to keep all the pairs with a given A value together in a sub-container so you can find their minimum. So just use a pair of nested loops. If you want, you can do it as a generator expression to calculate the minimum value nested inside a list comprehension, like this:

    A = [50, 60, 70]
    B = [0.3, 0.1, 0.5, 0.4]
    
    f = lambda x, y: x + y
    
    print [min(f(a,b) for b in B) for a in A]