Python 列表中最大元素的索引?
因此,我需要编写并测试一个函数,该函数返回列表中最大元素的索引(或者,如果几个元素的值最大,则返回其中第一个元素的索引),我不允许使用max函数Python 列表中最大元素的索引?,python,list,max,Python,List,Max,因此,我需要编写并测试一个函数,该函数返回列表中最大元素的索引(或者,如果几个元素的值最大,则返回其中第一个元素的索引),我不允许使用max函数 def largestElementIndex(lst): x=0 maxNum=0 while x+1 < len(lst): if lst[x] > maxNum: maxNum=x x+=1 return maxNum print "Progra
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最大元素索引(lst):
x=0
maxNum=0
当x+1maxNum:
maxNum=x
x+=1
返回最大值
打印“程序输出”
indexOfMax=最大元素索引([1,4,3,3,2])
打印“最大值索引为”,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
要使用max
执行此操作,请使用enumerate
的相同方法:
max_index = max(enumerate(lst), key=lambda pair: pair[1])[0]
您需要存储最大的数字和索引:
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
要使用max
执行此操作,请使用enumerate
的相同方法:
max_index = max(enumerate(lst), key=lambda pair: pair[1])[0]
如果不想使用max函数,也可以使用此简单方法:
res = lst.index(sorted(lst)[-1])
干杯 如果不想使用max函数,也可以使用此简单方法:
res = lst.index(sorted(lst)[-1])
干杯 此代码不起作用吗?此代码不起作用吗?第一个版本应具有
,而x
。当前,当最大值是列表的最后一个元素时,您将无法获得正确的结果。第一个版本应具有,而x
。当前,如果最大值是列表的最后一个元素,则无法获得正确的结果。