简体   繁体   中英

How do I use list comprehension to find the smallest value per column?

I have the following list:

List = 
[(1000, 1500),
 (2000, 2500), 
 (900, 3000)]

I want to find the smallest value for each column from the list.

Result = (900, 1500)

How do I use list comprehension to achieve this?

You don't need list comprehensions here, they don't really apply. You could do

Result = (min(List, key=lambda a: a[0])[0], min(List, key=lambda a: a[1])[1])

This will do it, although it doesn't use list comprehension:

list(map(min, zip(*List)))
[900, 1500]

zip(*List) will transpose the list, and the map function will find the minimum of the two elements.

As the previous answer said, you don't really need list comprehension. But in case you really do, you could do something like:

Result = (min([a[0] for a in List]), min([a[1] for a in List]))

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