1

所以我需要编写并测试一个函数,它返回列表中最大元素的索引(或者,如果几个元素具有最大值,则为其中第一个元素的索引)并且我不允许使用最大值功能。

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
4

2 回答 2

5

您需要存储最大的数字以及索引:

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]
于 2013-04-09T02:08:44.890 回答
1

如果您不想使用 max 函数,也可以使用这种简单的方法:

res = lst.index(sorted(lst)[-1])

干杯!

于 2013-04-09T04:07:00.697 回答