[英]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
实际上是2
, 1
是实际上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.