return highest value of lists
Question:
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
Answers:
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 iterableS argument has an implicit zip
-like effects on the iterables.
map(max, *(list1, list2, list3))
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 iterableS argument has an implicit zip
-like effects on the iterables.
map(max, *(list1, list2, list3))