繁体   English   中英

如何根据列号在嵌套列表及其索引中找到最大值?

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

假设我有以下列表列表: a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]] 1、7、2 a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]] 5、8、4 a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]] 6、3、9 a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]

我想在每一列中找到最大值,例如以下输出:

"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])

我尝试了max(enumerate(a), key=operator.itemgetter(1))但这返回(2, [6,3,9]) ,就像说嵌套列表在[0]位置的最大值是位于列表a索引[2]的那个。

zip列表,并在每个“子元组”上调用max

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

救援pandas

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))

如果要在以后重用最大值的“坐标”,则可以执行以下操作

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

要么

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

使用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])

和您期望的最终输出与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)]

在不使用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])

结果:

['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])']

我真的很喜欢@timegebzip答案,但是假设所有数组的长度相同,这是一个更简单的选择:

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]

换位列表并获得最大值的另一种方法:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM