Answers:
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
a.index(max(a))
会告诉您list的最大值元素的第一个实例的索引a
。
所选答案(以及大多数其他答案)需要至少两次通过列表。
这是一站式解决方案,对于较长的列表而言可能是更好的选择。
编辑:解决@John Machin指出的两个缺陷。对于(2),我尝试根据各种条件的估计发生概率和前辈的推论来优化测试。找出适当的初始化值max_val
并max_indices
在所有可能的情况下都可行,这有点棘手,特别是如果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
[]
广告宣传返回(“返回列表”)。代码应该简单if not seq: return []
。(2)循环中的测试方案不是最佳的:平均而言,在随机列表中,条件val < maxval
是最常见的,但是上面的代码进行了2次测试,而不是一次。
==
而不是2次-您的elif
条件将始终为真。
elif
自己,FWIW。;-)
我想出了以下内容,您可以通过看到它max
,min
以及其他类似列表中的功能:
因此,请考虑下一个示例列表,以找出最大值在列表中的位置a
:
>>> a = [3,2,1, 4,5]
使用发电机 enumerate
铸造
>>> list(enumerate(a))
[(0, 3), (1, 2), (2, 1), (3, 4), (4, 5)]
在这一点上,我们可以提取的位置最大值与
>>> 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)
我无法复制@martineau引用的@ SilentGhost-beating性能。这是我的比较工作:
=== 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
在Windows XP SP3上运行Python 2.7的老式笔记本电脑的结果:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
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
那就是我通常的做法。
查找最大列表元素索引的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
这是最大值及其出现的索引:
>>> 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]
heapq
-找到最大数量将是微不足道的。
heapq
解决方案,但我怀疑它是否可行。
如果要n
在名为的列表中获取最大数字的索引,则data
可以使用Pandas sort_values
:
pd.Series(data).sort_values(ascending=False).index[0:n]
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])
这段代码不像之前发布的答案那样复杂,但可以运行:
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将包含列表中最大数量的所有位置。
您可以通过多种方式进行操作。
传统的旧方法是
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中。