简体   繁体   中英

How to find max value in nested lists and its index, based on column number?

Supose I have this list of lists: a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]

I want to find the max value in each column, like the below output:

"Max value of column [0]": 6 (at index [2][0]) "Max value of column [1]": 8 (at index [1][1]) "Max value of column [2]": 9 (at index [2][2])

I tried max(enumerate(a), key=operator.itemgetter(1)) but this returns (2, [6,3,9]) , like saying that the nested list with the greatest value at its [0] position is the one located at index [2] of list a .

Transpose your list with zip and call max on every "sub-tuple".

>>> a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
>>> map(max, zip(*a))
[6, 8, 9]

pandas to the rescue

df = pd.DataFrame(a)
for k, i, m in  zip(df.columns, df.idxmax(), df.max()):

    print('"Max value of column [%i]": %i (at index [%i][%i]' % (k, m, k, i))

If you want to reuse the 'coordinate' of the maximum later, you could do something like

result = {k: (i, m,)  for k, i, m in  zip(df.columns, df.idxmax(), df.max()) }

or

result = {k: {'index': i, 'max': m,}  for k, i, m in  zip(df.columns, df.idxmax(), df.max()) }

A solution with numpy ,

In [27]: a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
In [28]: import numpy as np
In [29]: an = np.array(a)
In [30]: np.max(an,axis=0)
Out[30]: array([6, 8, 9])

And your desired final output with list comprehension + numpy

["Max value of column [%s]: %s (at index [%s][%s])" %(np.where(an == item)[1][0],item,np.where(an == item)[0][0],np.where(an == item)[1][0]) for item in np.max(an,axis=0)]

Without using list comprehension ,

for item in np.max(an,axis=0):
   indexs = np.where(an == item) 
   print "Max value of column [%s]: %s (at index [%s][%s])" %(indexs[0][0],item,indexs[0][0],indexs[1][0])

Result:

['Max value of column [0]: 6 (at index [2][0])',
 'Max value of column [1]: 8 (at index [1][1])',
 'Max value of column [2]: 9 (at index [2][2])']

I really like @timegeb 's answer with zip , but a more by-hand alternative, assuming that all the arrays are the same length:

a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
maxArray = []
for i in range(len(a[0])):
    maxArray.append(max([x[i] for x in a]))
print(maxArray)           # prints [6,8,9]

Another way of transposing your list and getting the max value:

a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]

[max([item[k] for item in a]) for k in range(len(a))]

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