Jak znaleźć wszystkie pozycje o maksymalnej wartości na liście?
Mam 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]
Max element to 55 (dwa elementy na pozycji 9 i 12)
Muszę znaleźć, na której pozycji (- ach) znajduje się maksymalna wartość. Proszę, pomóż.
17 answers
>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-21 15:17:24
a.index(max(a))
Powie Ci indeks pierwszej instancji największego wartościowego elementu listy a
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-21 15:17:02
Wybrana odpowiedź (i większość innych) wymaga co najmniej dwóch przejść przez Listę.
Oto rozwiązanie jednego przejścia, które może być lepszym wyborem dla dłuższych list.
Edited: aby zaradzić dwóm brakom wskazanym przez @ John Machin. Dla (2) starałem się zoptymalizować testy na podstawie guesstimated prawdopodobieństwo wystąpienia każdego warunku i wnioskowania dozwolone od poprzedników. To było trochę trudne dowiedzieć się prawidłowe wartości inicjalizacji dla max_val
i max_indices
który działał dla wszystkich możliwych przypadków, zwłaszcza jeśli Max był pierwszą wartością na liście - ale wierzę, że teraz tak.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-05 15:52:54
Wymyśliłem następujące i działa jak widać z max
, min
i inne funkcje nad takimi listami:
Więc proszę rozważyć następną przykładową listę znajdź pozycję maksimum na liście a
:
>>> a = [3,2,1, 4,5]
Korzystanie z generatora enumerate
i wykonanie odlewu
>>> list(enumerate(a))
[(0, 3), (1, 2), (2, 1), (3, 4), (4, 5)]
W tym momencie możemy wyodrębnić pozycję max Z
>>> max(enumerate(a), key=(lambda x: x[1]))
(4, 5)
Powyższe mówi nam, maksimum jest w pozycji 4 i jego wartość to 5.
Jak widzisz, w argumencie key
możesz znaleźć maksimum nad dowolnym iterowalnym obiektem, definiując lambda odpowiednią.
Mam nadzieję, że się przyczyni.
PD: jak zauważył @PaulOyster w komentarzu. Z Python 3.x
min
i max
pozwalają na użycie nowego słowa kluczowego default
, które unikają wyjątku raise ValueError
, gdy argument jest pustą listą. max(enumerate(list), key=(lambda x:x[1]), default = -1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-27 21:49:22
Nie mogę odtworzyć występu @ SilentGhost-beating cytowanego przez @ martineau. Oto mój wysiłek z porównaniami:
=== 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
Wyniki pobitego starego laptopa z Pythonem 2.7 NA Windows XP SP3:
>\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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-22 01:29:33
Również rozwiązanie, które daje tylko pierwszy wygląd , można uzyskać za pomocą numpy
:
>>> import numpy as np
>>> a_np = np.array(a)
>>> np.argmax(a_np)
9
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-05 10:01:00
Możesz również użyć pakietu numpy:
import numpy as np
A = np.array(a)
maximum_indices = np.where(A==max(a))
Zwróci tablicę numpy wszystkich indeksów, które zawierają wartość maksymalną
Jeśli chcesz zamienić to na listę:
maximum_indices_list = maximum_indices.tolist()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-15 07:57:39
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
Tak to zwykle robię.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-24 16:31:39
>>> max(enumerate([1,2,3,32,1,5,7,9]),key=lambda x: x[1])
>>> (3, 32)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-29 02:27:36
@shash odpowiedział na to gdzie indziej
Pythonicznym sposobem na znalezienie indeksu maksymalnego elementu listy będzie
position = max(enumerate(a), key=lambda x: x[1])[0]
Który wykonuje jedno przejście. Jednak jest wolniejszy niż rozwiązanie @Silent_Ghost, a tym bardziej @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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:32
Tylko jedna linijka:
idx = max(range(len(a)), key = lambda i: a[i])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-23 07:53:29
Oto maksymalna wartość i indeksy, na których się pojawia:
>>> 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]
[[2]} później: dla zadowolenia @ 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]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-21 17:47:13
Podobny pomysł ze zrozumieniem listy, ale bez wyliczenia
m = max(a)
[i for i in range(len(a)) if a[i] == m]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-26 07:03:48
Jeśli chcesz uzyskać indeksy największych liczb n
na liście o nazwie data
, możesz użyć Pandy sort_values
:
pd.Series(data).sort_values(ascending=False).index[0:n]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-15 09:44:08
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])
Ten kod nie jest tak wyrafinowany jak odpowiedzi zamieszczone wcześniej, ale będzie działał:
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 w powyższym kodzie zawiera wszystkie pozycje maksymalnej liczby na liście.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-13 14:38:29
Można to robić na różne sposoby.
Stary konwencjonalny sposób jest,
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
Inny sposób bez obliczania długości listy i przechowywania maksymalnej wartości do dowolnej zmiennej,
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)
Możemy to zrobić w Pythoniczny i inteligentny sposób! Korzystanie ze zrozumienia listy tylko w jednej linii,
maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
Wszystkie moje kody są w Pythonie 3.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-08 07:24:01