所以我需要编写并测试一个返回列表中最大元素索引的函数(或者,如果有几个元素具有最大值,则返回其中第一个元素的索引),但我不允许这样做使用最大函数。
def largestElementIndex(lst):
x=0
maxNum=0
while x+1 < len(lst):
if lst[x] > maxNum:
maxNum=x
x+=1
return maxNum
print "Program Output"
indexOfMax = largestElementIndex([1, 4, 3, 3, 2])
print 'Index Of Max Value is',indexOfMax
最佳答案
您需要存储最大数以及索引:
def largestElementIndex(lst):
x=0
maxNum=0
maxIndex=0
while x < len(lst):
if lst[x] > maxNum:
maxIndex=x
maxNum=lst[x]
x+=1
return maxIndex
我还会使用 for
循环:
def largestElementIndex(lst):
max_index = 0
max_value = lst[0]
for index, value in enumerate(lst)
if value > max_value:
max_index = index
max_value = value
return max_index
要用 max
做到这一点,你可以用同样的方式使用 enumerate
:
max_index = max(enumerate(lst), key=lambda pair: pair[1])[0]
关于python - 列表的最大元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15892100/