简体   繁体   中英

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]

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]

只需传递map两个列表参数即可:

c = map(min, a, b)

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)

eg:

>>> 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])

使用numpy的minimum函数,该函数对数组元素进行逐个元素的最小化。

numpy.minimum(a, b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM