找出 python 中子列表最大值的索引

Finding out indices of maxima of sublists in python

我有一个包含 n 个子列表的列表 x。我想制作一个长度为 n 的 new_list ,其中包含每个子列表的最大值索引。我怎样才能做到这一点?

例如:

x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]

(为了方便使用,我在每个子列表中取了相同的最大值)

因此输出必须是:

new_list = [4,1,0,3,2]

通过遍历并获取每个子列表的最大值来创建一个新列表:

像这样:

x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]

max_index = [i.index(max(i)) for i in x]

如果每个子列表中没有重复项,请尝试以下操作:

new_list = [sub.index(max(sub)) for sub in x]

>>> x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
>>> new_list = [sub.index(max(sub)) for sub in x]
>>> new_list
[4, 1, 0, 3, 2]
>>> 

您可以使用 lambda 表达式并映射到 l,以获取 x

中最大元素的索引
l=[[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]
print map(lambda x:x.index(max(x)),l)

输出:

[4, 1, 0, 3, 2]

如果您使用的是 numpy 数组,

>>> print map(lambda x:int(np.where(x==max(x))[0]),l)
[4, 1, 0, 3, 2]

如果您可以访问 numpy 就很容易了:

In [9]: import numpy as np

In [10]: x = [[1,4,2,3,5],[3,5,2,1,3],[5,2,1,4,3],[1,2,3,5,4],[4,1,5,2,3]]

In [11]: a = np.array(x) # Assumes all sublists are of the same length

In [12]: np.argmax(a, axis=1)
Out[12]: array([4, 1, 0, 3, 2])