Minoru
Minoru

Reputation: 1730

How to use list comprehension to select lower value between 2 lists?

a = list of number with length k
b = list of number with length k

How to get a list c with the lower value of a and b, position by position?

Example:
a = [0.6, 0.8, 0.4]
b = [0.4, 1.0, 0.5]

c = [0.4, 0.8, 0.4]

Upvotes: 1

Views: 1094

Answers (4)

tihom
tihom

Reputation: 8003

Using numpy's minimum function which does element-wise minimum of array elements.

numpy.minimum(a, b)

Upvotes: 1

amalloy
amalloy

Reputation: 92117

Just pass map two list arguments:

c = map(min, a, b)

Upvotes: 3

ettanany
ettanany

Reputation: 19816

You can use zip() like this:

c = [min(*item) for item in zip(a, b)]

Output:

>>> a = [0.6, 0.8, 0.4]
>>> b = [0.4, 1.0, 0.5]
>>>
>>> c = [min(*item) for item in zip(a, b)]
>>> c
[0.4, 0.8, 0.4]

Upvotes: 6

mgilson
mgilson

Reputation: 310097

This is a simple application of min and zip:

c = [min(aa, bb) for aa, bb in zip(a, b)]

If you're going to do computations like this a lot, it might be worth using numpy:

c = numpy.minimum(a, b)

e.g.:

>>> a = numpy.array([0.6, 0.8, 0.4])
>>> b = numpy.array([0.4, 1.0, 0.5])
>>> numpy.minimum(a, b)
array([ 0.4,  0.8,  0.4])

Upvotes: 1

Related Questions