简体   繁体   中英

return highest value of lists

Hello I have a few lists and im trying to create a new list of the highest values repsectively. for an example, these are the lists:

list1 = 5, 1, 4, 3
list2 = 3, 4, 2, 1
list3 = 10, 2, 5, 4

this is what I would like it to return:

[10, 4, 5, 4]

I thought that I could do a something like this:

largest = list(map(max(list1, list2, list3)))

but I get an error that map requires more than 1 argument.

I also thought I could write if, elif statements for greater than but it seems like it only does the first values and returns that list as the "greater value"

thanks for any help

This is the "zip splat" trick:

>>> lists = [list1, list2, list3]
>>> [max(col) for col in zip(*lists)]
[10, 4, 5, 4]

You could also use numpy arrays:

>>> import numpy as np
>>> np.array(lists).max(axis=0)
array([10,  4,  5,  4])

You have used map incorrectly. Replace that last line with this:

largest = list(map(max, zip(list1, list2, list3)))

In map , the first argument is the function to be applied, and the second argument is an iterable which will yield elements to apply the function on. The zip function lets you iterate over multiple iterables at once, returning tuples of corresponding elements. So that's how this code works!

Using map 's iterable S argument has an implicit zip -like effects on the iterables.

map(max, *(list1, list2, list3))

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