我有一个清单:
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)的最大值是位于。请帮助。
我有一个清单:
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, j in enumerate(a) if j == m]
[9, 12]
其他回答
你也可以使用numpy包:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
这将返回包含max值的所有下标的numpy数组
如果你想把它变成一个列表:
maximum_indices_list = maximum_indices.tolist()
这里是最大值和它出现的索引:
>>> 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]
还有一个解决方案,只给出第一个外观,可以通过使用numpy实现:
>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
你可以用不同的方法来做。
传统的方法是,
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的。