簡體   English   中英

在列表中查找最大值及其索引的 Pythonic 方法?

[英]Pythonic way to find maximum value and its index in a list?

如果我想要列表中的最大值,我可以只寫max(List) ,但是如果我還需要最大值的索引怎么辦?

我可以這樣寫:

maximum=0
for i,value in enumerate(List):
    if value>maximum:
        maximum=value
        index=i

但這對我來說看起來很乏味。

如果我寫:

List.index(max(List))

然后它將迭代列表兩次。

有沒有更好的辦法?

我認為接受的答案很好,但你為什么不明確地做呢? 我覺得更多人會理解你的代碼,這與 PEP 8 一致:

max_value = max(my_list)
max_index = my_list.index(max_value)

這種方法也比接受的答案快三倍左右:

import random
from datetime import datetime
import operator

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

if __name__ == "__main__":
    from timeit import Timer
    t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
          "import random; import operator;"
          "l = [random.random() for _ in xrange(100)]")
    print "Explicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

    t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
          "import random; import operator;"
          "l = [random.random() for _ in xrange(100)]")
    print "Implicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

在我的電腦上運行的結果:

Explicit: 8.07 usec/pass
Implicit: 22.86 usec/pass

其他套裝:

Explicit: 6.80 usec/pass
Implicit: 19.01 usec/pass

有很多選項,例如:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

假設列表非常大,並且假設它已經是 np.array(),這個答案比 @Escualo 快 33 倍。 我不得不降低測試運行的數量,因為測試正在查看 10000000 個元素,而不僅僅是 100 個。

import random
from datetime import datetime
import operator
import numpy as np

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

def npmax(l):
    max_idx = np.argmax(l)
    max_val = l[max_idx]
    return (max_idx, max_val)

if __name__ == "__main__":
    from timeit import Timer

t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
      "import random; import operator; import numpy as np;"
      "l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

我電腦上的結果:

Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass

使用 Python 的內置庫,這很容易:

a = [2, 9, -10, 5, 18, 9] 
max(xrange(len(a)), key = lambda x: a[x])

這告訴max使用自定義 function lambda x: a[x]找到列表[0, 1, 2, ..., len(a)]中的最大數字,它表示0實際上是21是實際上9

我會建議一個非常簡單的方法:

import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))

希望能幫助到你。

max([(v,i) for i,v in enumerate(my_list)])
max([(value,index) for index,value in enumerate(your_list)]) #if maximum value is present more than once in your list then this will return index of the last occurrence

如果最大值出現不止一次並且您想獲取所有索引,

max_value = max(your_list)
maxIndexList = [index for index,value in enumerate(your_list) if value==max(your_list)]

也許你仍然需要一個排序列表?

試試這個:

your_list = [13, 352, 2553, 0.5, 89, 0.4]
sorted_list = sorted(your_list)
index_of_higher_value = your_list.index(sorted_list[-1])

如果我想要一個列表中的最大值,我可以寫max(List) ,但是如果我還需要最大值的索引呢?

我可以這樣寫:

maximum=0
for i,value in enumerate(List):
    if value>maximum:
        maximum=value
        index=i

但這對我來說看起來很乏味。

如果我寫:

List.index(max(List))

然后它將迭代列表兩次。

有沒有更好的辦法?

我列出了一些大清單。 一個是列表,一個是 numpy 數組。

import numpy as np
import random
arrayv=np.random.randint(0,10,(100000000,1))
listv=[]
for i in range(0,100000000):
    listv.append(random.randint(0,9))

使用 jupyter notebook 的 %%time function 我可以比較各種事物的速度。

2秒:

%%time
listv.index(max(listv))

54.6 秒:

%%time
listv.index(max(arrayv))

6.71 秒:

%%time
np.argmax(listv)

103 毫秒:

%%time
np.argmax(arrayv)

numpy 的 arrays 非常快。

列表理解法:

假設您有一些列表List = [5,2,3,8]

然后[i for i in range(len(List)) if List[i] == max(List)]將是一個 pythonic 列表理解方法來查找值“i”,其中List[i] == max(List) .

它很容易擴展為 arrays 列表列表,只需執行 for 循環即可。

例如,使用列表“array”的任意列表並將“index”初始化為空列表。

array = [[5, 0, 1, 1], 
[1, 0, 1, 5], 
[0, 1, 6, 0], 
[0, 4, 3, 0], 
[5, 2, 0, 0], 
[5, 0, 1, 1], 
[0, 6, 0, 1], 
[0, 1, 0, 6]]
index = []

for List in array:
    index.append([i for i in range(len(List)) if List[i] == max(List)])
index

Output: [[0], [3], [2], [1], [0], [0], [1], [3]]

這是使用 Python 的內置函數對您的問題的完整解決方案:

# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",") 

# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers] 

# Loop through the list with a for-loop

for elements in numberL:
    maxEle = max(numberL)
    indexMax = numberL.index(maxEle)

print(maxEle)
print(indexMax)

暫無
暫無

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

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