我有一个清单:

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)的最大值是位于。请帮助。


当前回答

@shash在其他地方回答了这个问题

找到最大列表元素的索引的python方法是 Position = max(enumerate(a), key=lambda x: x[1])[0]

一个通过。然而,它比@Silent_Ghost的解决方案慢,甚至比@nmichaels的解决方案更慢:

for i in s m j n; do echo $i;  python -mtimeit -s"import maxelements as me" "me.maxelements_${i}(me.a)"; done
s
100000 loops, best of 3: 3.13 usec per loop
m
100000 loops, best of 3: 4.99 usec per loop
j
100000 loops, best of 3: 3.71 usec per loop
n
1000000 loops, best of 3: 1.31 usec per loop

其他回答

我想到了以下,它的工作原理,你可以看到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)

这里有一个简单的单步解决方案。

import math
nums = [32, 37, 28, 30, 37, 25, 55, 27, 24, 35, 55, 23, 31]

max_val = -math.inf
res = []

for i, val in enumerate(nums):
    if(max_val < val):
        max_val = val
        res = [i]
    elif(max_val == val):
        res.append(i)
print(res)
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
a.index(max(a))

会告诉你列表a中值最大的元素的第一个实例的索引。

import operator

def max_positions(iterable, key=None, reverse=False):
  if key is None:
    def key(x):
      return x
  if reverse:
    better = operator.lt
  else:
    better = operator.gt

  it = enumerate(iterable)
  for pos, item in it:
    break
  else:
    raise ValueError("max_positions: empty iterable")
    # note this is the same exception type raised by max([])
  cur_max = key(item)
  cur_pos = [pos]

  for pos, item in it:
    k = key(item)
    if better(k, cur_max):
      cur_max = k
      cur_pos = [pos]
    elif k == cur_max:
      cur_pos.append(pos)

  return cur_max, cur_pos

def min_positions(iterable, key=None, reverse=False):
  return max_positions(iterable, key, not reverse)

>>> L = range(10) * 2
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> max_positions(L)
(9, [9, 19])
>>> min_positions(L)
(0, [0, 10])
>>> max_positions(L, key=lambda x: x // 2, reverse=True)
(0, [0, 1, 10, 11])