简体   繁体   English

如何在Python的while循环中修复此错误?

[英]How to fix this error in while loop in Python?

I have a list in Python, list1 , and the following while loop: 我在Python中有一个列表, list1和以下while循环:

j = 0
while list1[j] >= list1[j - 1] and j < len(list1):
    # do something here and return k
    # k is always incremented
    j += k

I got the following error: IndexError: string index out of range 我收到以下错误: IndexError: string index out of range

How to fix this error? 如何解决这个错误?

You need to start your while condition with the length check. 您需要通过长度检查来启动while条件。 Python short-circuits the operations in your while loop, so when j is too large, it will just throw an error rather than gracefully ending the loop. Python会缩短 while循环中的操作,因此,当j太大时,它将抛出一个错误,而不是优雅地结束循环。 So like this: 像这样:

while j < len(list1) and list1[j] >= list1[j - 1]:

Your first iteration of the loop is comparing list1[0] and list1[-1] , which is valid , but may not be what you want to be doing (it compares the first and last elements of list1 ). 循环的第一个迭代是比较list1[0]list1[-1] ,这是有效的 ,但可能不是您想要做的(它比较list1的第一个和最后一个元素)。 Depending on your goals, you may or may not wish to start your loop with j = 1 . 根据您的目标,您可能希望也可能不希望以j = 1开始循环。

When using an and , if the first condition is false, the second is not even checked. 当使用and ,如果第一个条件为假,则甚至不检查第二个条件。 Simply use: 只需使用:

j = 0
while j < len(list1) and list1[j] >= list1[j - 1]:
    # do something here and return k
    # k is always incremented
    j += k

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

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