我有一个清单:
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)的最大值是位于。请帮助。
当前回答
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])
其他回答
只有一句话:
idx = max(range(len(a)), key = lambda i: a[i])
你也可以使用numpy包:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
这将返回包含max值的所有下标的numpy数组
如果你想把它变成一个列表:
maximum_indices_list = maximum_indices.tolist()
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]
import pandas as pd
pd.Series(a).idxmax()
9
我通常都是这么做的。
类似的想法与列表理解,但没有枚举
m = max(a)
[i for i in range(len(a)) if a[i] == m]
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)