【问题标题】:How to find max value in nested lists and its index, based on column number?如何根据列号在嵌套列表及其索引中查找最大值?
【发布时间】:2017-05-20 01:31:35
【问题描述】:

假设我有这个列表列表: 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] 的嵌套列表。

【问题讨论】:

  • 你还需要最大值的'坐标'吗?
  • 如果你指的是索引,是的,因为我在另一个函数中需要它们

标签: python max nested-lists


【解决方案1】:

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

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

【讨论】:

  • @RahulKP 请仅在您知道自己在做什么时才编辑帖子。 zip 返回元组列表(或 Python 3 中的元组迭代器),而不是列表。
【解决方案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]

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

        另一种转置列表并获得最大值的方法:

        a = [[1, 7, 2], [5, 8, 4], [6, 3, 9]]
        
        [max([item[k] for item in a]) for k in range(len(a))]
        

        【讨论】:

          猜你喜欢
          • 2011-09-05
          • 2015-10-24
          • 1970-01-01
          • 2018-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多