Reputation: 872
This is the list i am dealing with. Value:
[[0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.94, 0.0, 0.0, 0.63, 0.0],
[0.51, 0.51],
[0.54, 0.54, 0.0, 0.0,0.63, 0.0, 0.51, 0.54, 0.51, 1.0, 0.51],
[0.81,0.05, 0.13, 0.7, 0.02]]
I have tried to find the highest value belongs to which list. Here the highest value is 1 and its in third list. ie, index 2. How to get this?
maxval=[]
maxval1=[]
for i in range(0,len(Value)):
maxval1.append(max(Value[i]))
maxval.append(max(maxval1))
maxval1
Out[220]: [0.94, 0.51, 1.0, 0.81]
maxval
Out[221]: [1.0]
index=[]
index1=[]
for i in range(0,len(Value)):
index1.append(Value[i].index(maxval))
gives error: ValueError: [1.0] is not in list
Upvotes: 3
Views: 60
Reputation: 51643
You can do this as kindof one-liner as well:
data = [[0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.94, 0.0, 0.0, 0.63, 0.0],
[0.51, 0.51],
[0.54, 0.54, 0.0, 0.0,0.63, 0.0, 0.51, 0.54, 0.51, 1.0, 0.51],
[0.81,0.05, 0.13, 0.7, 0.02]]
# iL === innerList, abbreviated for 79 chars line width
max_idx, max_value = max( enumerate(max(iL) for iL in data), key = lambda x:x[1])
print(max_idx)
Output:
2 # max_value == 1, but not printed
The trick is to get the max(..)
of each inner list, enumerate()
those and use another max(iterable, key=...)
that has a key
that selects the highest value (not position) of the enumerate tuple (position,value)
.
Advantage - its using generators:
you do not create any intermediary lists but soley work with generators - for big lists this is far more memory friendly then then creating a list like infiQuanta does.
Upvotes: 1
Reputation: 34046
You can solve this using the Python's library pandas
. Solution becomes really simple:
Create a dataframe
(df) from your list:
In [2040]: df = pd.DataFrame(Value)
In [2041]: df
Out[2041]:
0 1 2 3 4 5 6 7 8 9 10
0 0.25 0.00 0.00 0.0 0.00 0.0 0.94 0.00 0.00 0.63 0.00
1 0.51 0.51 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 0.54 0.54 0.00 0.0 0.63 0.0 0.51 0.54 0.51 1.00 0.51
3 0.81 0.05 0.13 0.7 0.02 NaN NaN NaN NaN NaN NaN
Now, just find max among each row:
In [2047]: df.max(axis = 1)
Out[2047]:
0 0.94
1 0.51
2 1.00
3 0.81
Above, you can see max
of all rows.
Now, find the max
value from the above. That will be the max of the whole Dataframe.
In [2048]: df.max(axis = 1).max()
Out[2048]: 1.0
To, find the index of this value:
In [2082]: pd.DataFrame(Value).max(axis = 1).idxmax()
Out[2082]: 2
Let me know if this helps.
Upvotes: 0
Reputation: 106
You are searching for max value in each list, but it is present in third list only, this will throw ValueError
for all other lists unless max value is present in first list itself.
It can be done simply like this
max_list = list()
for i, sub_list in enumerate(Value):
max_list.append((max(sub_list), i))
index_of_max = max(max_list)[1]
index_of_max
provides index of list containing max value.
Upvotes: 3