简体   繁体   English

IndexError:使用while循环列出索引超出范围

[英]IndexError: list index out of range with a while loop

I've been trying to fix this but the same error message came up every time: 我一直试图解决这个问题,但每次都会出现同样的错误消息:

while number_list[i] <= number_list[j]: 而number_list [i] <= number_list [j]:

IndexError: list index out of range IndexError:列表索引超出范围

I've searched for the same type of bug, but not very similar cases found. 我搜索了相同类型的错误,但找不到非常相似的情况。

Here it is the head program (orders the numbers of my list, from the little one to the bigger): 这是头程序(订购我的清单编号,从小编到大编):

    number_list=[]

list_lenght=int(input("List lenght: "))

while len(number_list)<list_lenght:
    item=input("Enter new item to the list:")
    number_list.append(item)
    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    i=0
    j=1
    while (j)<=(len(number_list)-1):
        while number_list[i]<=number_list[j]:
            j=j+1
        i=j
        j=i+1
    final_item=number_list[i]
    number_list_final.append(final_item)`
    del number_list[i] 
    order_number_list(number_list)

order_number_list(number_list)
print(number_list_final)

I know this is about iterating with the list while modifying it, but no idea how to fix it. 我知道这是关于在修改它时迭代列表,但不知道如何修复它。

Can anyone help me to debug this, or give me some tips? 任何人都可以帮我调试这个,还是给我一些提示?

Thank you! 谢谢!

If I understand you correctly, you're trying to sort a list of numbers. 如果我理解正确的话,你会尝试对数字列表进行排序。 There's a built-in Python method for this, that has been optimized for ages to be fast and use minimal memory, it's called sorted . 有一个内置的Python方法,它已被优化为多年来快速和使用最小的内存,它被称为sorted

Instead of running order_number_list , try: 而不是运行order_number_list ,尝试:

print(sorted(number_list))

If this is some kind of homework, and you're not allowed to use the built-in sorted , for educational purposes I would recommend you to use a sorting algorithm called bubble sort, more information here - Bubble Sort Homework . 如果这是某种功课,并且你不允许使用内置sorted ,出于教育目的,我建议你使用一种名为冒泡排序的排序算法,这里有更多信息 - 冒泡排序家庭作业

Updating your code to include a couple of print statements shows that the j increases to past the length of the list. 更新代码以包含几个打印语句会显示j增加到超过列表的长度。 Then the "while number_list[i]<=number_list[j]:" no longer can be completed as there is no "number_list[j]" for the j value. 然后“while number_list [i] <= number_list [j]:”不再可以完成,因为j值没有“number_list [j]”。

number_list=[1,2,3,4,5]

list_lenght=5
#=int(input("List lenght: "))

#while len(number_list)<list_lenght:
#    item=input("Enter new item to the list:")
#    number_list.append(item)
#    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    i=0
    j=1
    while (j)<=(len(number_list)):
        while number_list[i]<=number_list[j]:
            print (j)
            print (i)
            j=j+1
        i=j
        j=i+1
    final_item=number_list[i]
    number_list_final.append(final_item)
    del number_list[i] 
    order_number_list(number_list)

order_number_list(number_list)
print(number_list_final)

This outputs : 这输出:

That's your number list:  [1, 2, 3, 4, 5]
1
0
2
0
3
0
4
0
Traceback (most recent call last):
  File "C:/Python3/numberlist.py", line 30, in <module>
    order_number_list(number_list)
  File "C:/Python3/numberlist.py", line 19, in order_number_list
    while number_list[i]<=number_list[j]:
IndexError: list index out of range

The code is falling over once j is 5 for this example, it is trying to compare to a number that doesnt exist 对于此示例,一旦j为5,代码就会失败,它试图与不存在的数字进行比较

number_list=[]

list_lenght=int(input("List length: "))

while len(number_list)<list_lenght:
    item=input("Enter new item to the list:")
    number_list.append(int(item))
    print(number_list)

print("That's your number list: ",number_list)

number_list_final=[]

def order_number_list(number_list):
    current_low = ["number"]
    current_low[0] = number_list[0]
    x = 1
    current_low_pos = 0
    while x < len(number_list):
        if current_low[0] > number_list[x]:
            current_low[0] = number_list[x]
            current_low_pos = x
        x = x + 1
    del number_list[current_low_pos]

    if number_list == []:
        remaining_list = []
    else:
        remaining_list = order_number_list(number_list)

    return (current_low + remaining_list)
number_list_final = order_number_list(number_list)
print(number_list_final)

This is code that has been clarified and corrected. 这是已经澄清和纠正的代码。 j was not working right, as other answers have pointed out. 正如其他答案所指出的那样,j无法正常工作。

number_list.append(item)

needed to be changed to: 需要改为:

number_list.append(int(item))

because you cant compare strings with the '<' operator. 因为你无法将字符串与'<'运算符进行比较。

I also added a return statement, added this line of code: 我还添加了一个return语句,添加了这行代码:

number_list_final = order_number_list(number_list)

because your final print statement would print an empty list because: 因为你的最后一个print语句会打印一个空列表,因为:

order_number_list(number_list)

doesn't change the variable number_list_final. 不会更改变量number_list_final。

I changed some of the function code to simply and make it more readable. 我将一些功能代码改为简单,使其更具可读性。

It also explicitly sets the current lowest item to be the first, and changes that if a lower item is found later on. 它还明确地将当前最低项目设置为第一项,并在稍后找到较低项目时进行更改。

Hope this helps, let me know if you have any questions! 希望这有帮助,如果您有任何疑问,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM