Python 如何在列表中找到最大值的所有位置?
我有一份清单:Python 如何在列表中找到最大值的所有位置?,python,list,max,Python,List,Max,我有一份清单: 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上有两个元件) 我需要找到最大值所在的位置。请帮忙 a.index(max(a)) 将告诉您列表中最大值元素的第一个实例的索引a以下是最大值及其出现的索引: >>> m = max(a) >&
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上有两个元件)
我需要找到最大值所在的位置。请帮忙
a.index(max(a))
将告诉您列表中最大值元素的第一个实例的索引
a
以下是最大值及其出现的索引:
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
>>> 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]
后来:为了@silenghost的满意
>>> 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]
所选答案(以及大多数其他答案)至少需要两次通过列表。这里有一个一次性解决方案,对于较长的列表可能是更好的选择 编辑:以解决@John Machin指出的两个缺陷。对于(2),我试图根据每种情况发生的猜测概率和前人允许的推论来优化测试。计算
max_val
和max_index
的正确初始化值有点棘手,这在所有可能的情况下都有效,特别是当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
我无法重现@martineau引用的@silenghost击败对手的表演。以下是我在比较方面的努力: ==maxelements.py===
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]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(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
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
类似的想法与列表理解,但没有枚举
m = max(a)
[i for i in range(len(a)) if a[i] == m]
您还可以使用numpy软件包:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
这将返回包含最大值的所有索引的numpy数组
如果要将其转换为列表:
maximum_indices_list = maximum_indices.tolist()
我提出了以下内容,正如您可以看到的那样,它适用于
max
、min
和类似列表的其他函数:
>请考虑下一个示例列表,找出列表< <代码> < < /代码>:
中<强>最大< /强>的位置>>> a = [3,2,1, 4,5]
使用生成器枚举
并进行转换
>>> list(enumerate(a))
[(0, 3), (1, 2), (2, 1), (3, 4), (4, 5)]
此时,我们可以使用
上面告诉我们,最大值在位置4,他的值是5
如您所见,在key
参数中,您可以通过定义一个合适的lambda来找到任何iterable对象的最大值
我希望它有所贡献
PD:正如@PaulOyster在评论中指出的那样。使用
python3.x
时,min
和max
允许使用新关键字default
,以避免参数为空列表时出现raise异常ValueError
<代码>最大值(枚举(列表),键=(lambda x:x[1]),默认值=-1)此代码没有前面发布的答案那么复杂,但它可以工作:
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将包含列表中最大数字的所有位置。只有一行:
idx = max(range(len(a)), key = lambda i: a[i])
查找最大列表元素索引的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
我通常就是这样做的。你可以用各种方式来做 传统的做法是,
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和smart的方式来做!在一行中使用列表理解
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
我的所有代码都是Python 3。如果您想获得名为
数据的列表中最大的n
数字的索引,可以使用:
另外,使用numpy
,也可以实现仅给出第一次外观的解决方案:
>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9
不过,这只会得到第一个实例,他要求提供找到最大值的所有索引。在每种情况下,您必须使用slice循环获取剩余的列表,并在不再找到异常时处理异常。我确实提到过,它只会给出第一个实例。如果你想要所有这些,SilentGhost的解决方案更漂亮,也更不容易出错。至少在我谈到这个问题时,这个问题明确要求在有多个最大值的情况下列出一个列表……从技术上讲,你可以使用它来获得最大值元素的第一个实例,然后将其设置为一个大得离谱的负数,然后找到下一个最大值的元素,但这太复杂了,它显式地表示“all”。请不要发垃圾邮件,这里的目标是帮助人们尽快避免获得徽章和声誉(如果你真的想帮忙,请删除你的答案)。你确实意识到这是多么低效?合理化:(1)“过早优化是……等等”(2)这可能不重要。(3) 这仍然是一个很好的解决方案。也许我会将其重新编码为使用heapq
——找到最大值将是微不足道的。虽然我很想看到您的heapq
解决方案,但我怀疑它是否会起作用。如果您不介意多次遍历列表的话,这是一个很好的简短答案——很可能。除了大的0,对于这是2n,列表将通过2x进行迭代,一旦确定最大值,再找一次查找最大值的位置。A for循环跟踪当前的最大值及其位置对于非常长的列表可能更有效。@radtek big O只是n。前导系数在大运算中被忽略理论上O(N)和O(2N)是相同的,但实际上,O(N)的运行时间肯定会更短,特别是当N接近无穷大时。(1)空列表处理需要注意。应按公布的方式返回[]
(“返回列表”)。代码应该是如果不是seq:return[]
。(2) 循环中的测试方案是次优的:平均而言,在随机列表中,条件val
将是最常见的,但上面的代码需要进行2次测试,而不是一次测试。@John Machin的注释+1,用于捕获与文档字符串的不一致性,并且不允许我发布次优代码。说实话,既然一个答案已经被接受了,我就失去了一点继续研究我的答案的动力,因为我认为几乎没有人会进一步研究它——而且它比我想象的要长得多
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
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
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)
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
pd.Series(data).sort_values(ascending=False).index[0:n]
>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9