我有一个清单:

a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]

最大元素是55(两个元素在位置9和12)

我需要找到在哪个位置(s)的最大值是位于。请帮助。


当前回答

类似的想法与列表理解,但没有枚举

m = max(a)
[i for i in range(len(a)) if a[i] == m]

其他回答

这段代码不像之前发布的答案那么复杂,但它可以工作:

m = max(a)
n = 0    # frequency of max (a)
for number in a :
    if number == m :
        n = n + 1
ilist = [None] * n  # a list containing index values of maximum number in list a.
ilistindex = 0
aindex = 0  # required index value.    
for number in a :
    if number == m :
        ilist[ilistindex] = aindex
        ilistindex = ilistindex + 1
    aindex = aindex + 1

print ilist

上面代码中的Ilist将包含列表中最大数目的所有位置。

你可以用不同的方法来做。

传统的方法是,

maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a)       #calculate length of the array

for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
    if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
        maxIndexList.append(i)

print(maxIndexList) #finally print the list

另一种不计算列表长度并将最大值存储到任何变量的方法是,

maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
    if i==max(a): #max(a) returns a maximum value of list.
        maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index

print(maxIndexList)

我们可以用python和聪明的方式来做!在一行中使用列表理解,

maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index

我所有的代码都是Python 3的。

我想到了以下,它的工作原理,你可以看到max, min和其他函数的列表,像这样:

那么,请考虑下面的例子列表找出最大值在列表中的位置a:

>>> a = [3,2,1, 4,5]

使用生成器枚举并进行强制转换

>>> list(enumerate(a))
[(0, 3), (1, 2), (2, 1), (3, 4), (4, 5)]

此时,我们可以提取max的位置

>>> max(enumerate(a), key=(lambda x: x[1]))
(4, 5)

上面告诉我们,最大值在位置4,他的值是5。

如您所见,在key参数中,您可以通过定义适当的lambda来找到任何可迭代对象的最大值。

我希望它能有所帮助。

PD:正如@PaulOyster在评论中指出的那样。使用Python 3。x的min和max允许一个新的关键字default,避免引发异常ValueError当参数是空列表。Max (enumerate(list), key=(lambda x:x[1]), default = -1)

只有一句话:

idx = max(range(len(a)), key = lambda i: a[i])

选择的答案(和大多数其他答案)需要至少两次遍历列表。 这里有一个一次性的解决方案,对于较长的列表可能是一个更好的选择。

编辑:解决@John Machin指出的两个不足之处。对于(2),我尝试基于每个条件发生的猜测概率和前人允许的推论来优化测试。为max_val和max_indexes确定正确的初始化值有点棘手,这适用于所有可能的情况,特别是如果max恰好是列表中的第一个值-但我相信它现在做到了。

def maxelements(seq):
    ''' Return list of position(s) of largest element '''
    max_indices = []
    if seq:
        max_val = seq[0]
        for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val):
            if val == max_val:
                max_indices.append(i)
            else:
                max_val = val
                max_indices = [i]

    return max_indices