简体   繁体   English

IndexError:字符串索引超出范围没有意义

[英]IndexError: string index out of range doesn't make sense

I have a problem that i can't explain, I'm making a program to find the "longest common prefix" and I got an error IndexError: string index out of range.我有一个无法解释的问题,我正在编写一个程序来查找“最长的公共前缀”,但出现错误IndexError: string index out of range.

I noticed that changing the order on an if statement was the solution, but that doesn't make sense for me.我注意到更改 if 语句的顺序是解决方案,但这对我来说没有意义。

This line was:这条线是:

if default[j] == list[i][j] and j < len(default):

The solution to the problem is:问题的解决方法是:

    if j < len(default) and default[j] == list[i][j]:

Why does this happen, isn't it the same?为什么会这样,不是一样的吗? Am I blind?我瞎了吗?

This is the code with the error:这是有错误的代码:

list=["hola", "holo", "holi"]
default=list[0]

for i in range(1, len(list)):
    temp=""
    if len(default)==0:
        break;

    for j in range(len(list[i])):
        if default[j] == list[i][j] and j < len(default):
            temp+=default[j]
        else:
            break

    default=temp
print(default)

Order matter when using and operator.使用and运算符时的顺序很重要。

a and b

If a is true then only b is checked.如果 a 为真,则仅检查 b。 It doesn't matter if b consist of an error (except syntax error). b 是否包含错误并不重要(语法错误除外)。

The two statements are not the same.两种说法并不相同。

if we have a condition statement如果我们有一个条件语句

if Condtion1 and Condetion2:

Conditon2 will be checked if and only if Condtion1 is True.当且仅当 Condtion1 为真时,才会检查 Conditon2。

Let us examine the folowing short examples, and it will be clear:让我们检查以下简短示例,就会清楚:

a=10
b=0
if b!=0 and a/b>3:
   print('Do Something')
else:
   print('ok')

The output will be ok ok就可以了

But, if we reorder the condtions in if statement if a/b>3 and b:=0:但是,如果我们对 if 语句中的条件重新排序, if a/b>3 and b:=0:

a=10
b=0
if a/b>3 and b!=0:
   print('Do Something')
else:
   print('ok')

The later code give error ZeroDivisionError: division by zero , where, a/b was examined first and the fact the b is equal to 0.后面的代码给出错误ZeroDivisionError: division by zero ,其中,首先检查 a/b 并且 b 等于 0。

But, in the first code, the conditon b,=0 was examined first, and gives False , so the second condition a/b>3 was not processed.但是,在第一个代码中,条件 b,=0 首先被检查,并给出False ,所以第二个条件a/b>3没有被处理。

So, the two statements are not the same.所以,这两个说法是不一样的。

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

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