簡體   English   中英

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

[英]How to find all positions of the maximum value in a 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]

最大元素為 55(位置 9 和 12 上的兩個元素)

我需要找到最大值位於哪個位置。 請幫忙。

a.index(max(a))

將告訴您列表a的最大值元素的第一個實例的索引。

>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]

選擇的答案(和大多數其他答案)需要至少兩次通過列表。
這是一個一次性解決方案,它可能是更長列表的更好選擇。

編輯:解決@John Machin 指出的兩個缺陷。 對於(2),我嘗試根據每個條件的估計發生概率和前輩允許的推斷來優化測試。 找出適用於所有可能情況的max_valmax_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

我想出了以下內容,正如您在maxmin和其他類似列表上的函數所看到的那樣:

因此,請考慮下一個示例列表,找出列表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.xminmax允許使用新的關鍵字default ,以避免在參數為空列表時引發異常ValueError max(enumerate(list), key=(lambda x:x[1]), default = -1)

還有一個解決方案,它只給出了第一個外觀,可以通過使用numpy來實現:

>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9

我無法重現@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

您還可以使用 numpy 包:

import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))

這將返回包含最大值的所有索引的 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

這就是我通常這樣做的方式。

>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)

@shash 在別處回答了這個問題

查找最大列表元素索引的 Pythonic 方法是

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

只有一行:

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

具有列表理解但沒有枚舉的類似想法

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

這是最大值及其出現的索引:

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

如果要獲取名為data的列表中最大n數字的索引,可以使用 Pandas sort_values

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

這是一個簡單的單程解決方案。

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)

這段代碼不像之前發布的答案那么復雜,但它可以工作:

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將包含列表中最大數字的所有位置。

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

您可以通過多種方式做到這一點。

舊的傳統方式是,

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 中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM