如何在列表中找到所有最大值的位置?

217
  • Item 1
  • Item 2
  • Item 3

  • 项目1
  • 项目2
  • 项目3
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上有两个元素)

我需要找出最大值位于哪些位置。请帮忙。

18个回答

3

仅一行:

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

不错,但它只返回第一个索引,而非全部索引。 - iggy

2

如果你想获取名为 data 的列表中最大的 n 个数字的索引,可以使用Pandas的 sort_values 函数:

pd.Series(data).sort_values(ascending=False).index[0:n]

2

这是最大值及其出现的索引:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> 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]
>>> for i, x in enumerate(a):
...     d[x].append(i)
... 
>>> k = max(d.keys())
>>> print k, d[k]
55 [9, 12]

稍后:为了满足@SilentGhost的需求。
>>> from itertools import takewhile
>>> import heapq
>>> 
>>> def popper(heap):
...     while heap:
...         yield heapq.heappop(heap)
... 
>>> 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]
>>> h = [(-x, i) for i, x in enumerate(a)]
>>> heapq.heapify(h)
>>> 
>>> largest = heapq.heappop(h)
>>> indexes = [largest[1]] + [x[1] for x in takewhile(lambda large: large[0] == largest[0], popper(h))]
>>> print -largest[0], indexes
55 [9, 12]

你知道这样是多么低效吗? - SilentGhost
1
合理化解释:(1)“过早优化是万恶之源……等等。”(2)可能并不重要。(3)这仍然是一个好的解决方案。也许我会重新编码它,使用heapq——在那里找到最大值将是微不足道的。 - hughdbrown
虽然我很想看到你用heapq解决问题,但我怀疑它是否有效。 - SilentGhost

2

与列表推导式类似,但不使用enumerate函数

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

我不是那个给你点踩的人,但请注意这种写法不太好看,而且性能也不佳:在Python中通过索引进行迭代比直接遍历列表要麻烦得多,应该尽量避免。此外,由于a[i]的调用,它肯定比使用enumerate的解决方案慢。 - yo'

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)

0
您可以用多种方式来实现它。
传统的老方法是:
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)

我们可以用Pythonic和聪明的方式来完成!只需在一行中使用列表推导式,
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index

我所有的代码都是用Python 3编写的。


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

0

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

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 在上述代码中将包含列表中最大数的所有位置。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接