I am new to Python, so please help.
I need to find the max element and it's index in a two-dimensinal list, but I need to search only one column. It is better to explain using example:
Initial list of lists:
a = [[1.0, 1.0], [2.0, 2.0], [4.0, 4.0], [8.0, 1.0]]
I need to search the position x in a, where a[x][1] will be max in a[x][1]. So I don't need to search for a max in a "specified column".
The output must give x = 2, because
a[2][1] == 4
I don't want to scan all the list in a cycle manually, I am searching for the elegant way in Python.
What approach should I use?
I have tried to use
max = max(a)
print(max)
but it gives a [8.0, 1.0] output - the element of a list with the maximum element inside.
OR for example,
max2 = np.max(a, axis=1)
max2_indexes = np.argmax(a, axis=1)
print(max2)
print(max2_indexes)
that outputs for provided data
[4. 2. 1. 8.] [0 0 0 0]
I am suggesting to use Numpy axis=0 parameter but maybe there is a more naive way of doing this without cycles?
max2_indexes = np.argmax(a, axis=0)
In this case I have a right answer [3 2]
, but maybe it's a wrong approach?
(The real list is very large - about 100000 of "small lists")
CodePudding user response:
In [2]: a = [[1.0, 1.0], [2.0, 2.0], [4.0, 4.0], [8.0, 1.0]]
A "transpose" of such a nested list is:
In [3]: a1 = list(zip(*a))
In [4]: a1
Out[4]: [(1.0, 2.0, 4.0, 8.0), (1.0, 2.0, 4.0, 1.0)]
And from that you can easily get the max of "2nd column":
In [5]: a1[1]
Out[5]: (1.0, 2.0, 4.0, 1.0)
In [6]: max(a1[1])
Out[6]: 4.0
or we can just get the 2nd column with a simple list comprehension:
In [13]: max([i[1] for i in a])
Out[13]: 4.0
numpy
makes treating rows and columns like this easier - but at the expense of converting the list to array:
In [7]: A= np.array(a)
In [8]: A.max(axis=0)
Out[8]: array([8., 4.])
and it makes finding the index easier:
In [9]: A.argmax(axis=0)
Out[9]: array([3, 2], dtype=int64)
You can select the 2nd column either before or after the argmax
:
In [10]: A.argmax(axis=0)[1]
Out[10]: 2
In [11]: A[:,1].argmax()
Out[11]: 2
CodePudding user response:
You can get the maximum value in a nested list by using max function :
max(a,key = lambda x:x[1])
#output
[4.0, 4.0]
Now, when you have the maximum value you can find the index by using enumerate and looping:
for x,y in enumerate(a):
if y==max(a,key = lambda x:x[1]):
print(x)
#output
2