0

I have this list:

dCF3v=[[(1.90689635276794, -44704.76171875)],
       [(1.90689635276794, -44705.76171875)],
       [(1.90689635276794, -44706.76171875)],
       [(1.90689635276794, -44707.76171875)]
      ]

I'd like to know the index of the row where the maximum value is. In the example above: row index 3.

I already have a code for finding the maximum value:

CF3a = (abs(x[0][1]) for x in dCF3v)
CF3 = max(CF3a)

If possible I'd like to adapt this code and not have to do the classic for and if loops.

4

2 回答 2

2

您可以使用enumerate保留索引和key参数max来寻找正确的值:

dCF3v=[[(1.90689635276794, -44704.76171875)],
       [(1.90689635276794, -44705.76171875)],
       [(1.90689635276794, -44706.76171875)],
       [(1.90689635276794, -44707.76171875)]
      ]

CF3a = (abs(x[0][1]) for x in dCF3v)
index, value = max(enumerate(CF3a), key=lambda (index, value): value)
print index,value
于 2013-05-02T16:26:51.550 回答
1

由于您的数据本质上看起来是数字的,我强烈建议您使用numpy模块,因为它的设计部分是为了满足您的要求。

您可以将数据转换为 numpy 数组

import numpy as np
data = np.array(dCF3v)

然后用于np.argmax查找最大值的索引

idx = np.argmax(data)

这为您提供了扁平数组的索引。如果您知道数组的形状,则此展平索引很容易使用模运算转换为行号。您可以像这样获取行数和列数

rows,cols = data.shape

然后是模除的行号

maxRow = idx%cols

numpy 还有一个名为的函数unravel_index,它为你做模运算,

row, col = np.unravel_index(idx, data.shape)
于 2013-05-02T17:23:22.263 回答