首页 > 解决方案 > Python-为什么我的列表索引超出范围错误?

问题描述

我正在为列表的第 i 个元素设置一个变量,但即使在第一次迭代中我也会出现超出范围的错误。

# code the max() function


def maxinlist(yourlist):
    first = 0
    second = 0
    duplicatelist = yourlist
    for i in range(0, len(yourlist) - 1):
        first = yourlist[i]

        for j in range(len(yourlist) - 1, 0, -1):
            second = yourlist[j]

            if second > first:
                duplicatelist.pop(i)
            elif first > second:
                duplicatelist.pop(j)

    print(duplicatelist[0])


mylist = [1, 4, 8, 2, 5, 100, 44, 2, 5]
maxinlist(mylist)

标签: pythonlist

解决方案


确保在更改主列表时克隆列表duplicatelist

更改以下内容

duplicatelist = yourlist

duplicatelist = yourlist[:]

推荐阅读