Reputation: 95
I've a list x
of n sublists. I want to make a new_list
of length n containing the indices of maximum of each sublist. How can I pull this off?
For example:
x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
(I've taken the maxima the same in each sublist for the ease of use)
And the output must hence be:
new_list = [4,1,0,3,2]
Upvotes: 0
Views: 947
Reputation: 3787
You can use lambda expression and map over l, to get the index of max element in x
l=[[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
print map(lambda x:x.index(max(x)),l)
Output:
[4, 1, 0, 3, 2]
If you are using numpy array,
>>> print map(lambda x:int(np.where(x==max(x))[0]),l)
[4, 1, 0, 3, 2]
Upvotes: 1
Reputation: 1321
Make a new list by looping through and getting the max of each sublist:
Like so:
x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
max_index = [i.index(max(i)) for i in x]
Upvotes: -1
Reputation: 86178
If you have access to numpy
it is very easy:
In [9]: import numpy as np
In [10]: x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
In [11]: a = np.array(x) # Assumes all sublists are of the same length
In [12]: np.argmax(a, axis=1)
Out[12]: array([4, 1, 0, 3, 2])
Upvotes: 1
Reputation: 19264
Provided there are no duplicate items in each sublist, try the following:
new_list = [sub.index(max(sub)) for sub in x]
>>> x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
>>> new_list = [sub.index(max(sub)) for sub in x]
>>> new_list
[4, 1, 0, 3, 2]
>>>
Upvotes: 1