繁体   English   中英

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

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

我有一个无法解释的问题,我正在编写一个程序来查找“最长的公共前缀”,但出现错误IndexError: string index out of range.

我注意到更改 if 语句的顺序是解决方案,但这对我来说没有意义。

这条线是:

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

问题的解决方法是:

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

为什么会这样,不是一样的吗? 我瞎了吗?

这是有错误的代码:

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)

使用and运算符时的顺序很重要。

a and b

如果 a 为真,则仅检查 b。 b 是否包含错误并不重要(语法错误除外)。

两种说法并不相同。

如果我们有一个条件语句

if Condtion1 and Condetion2:

当且仅当 Condtion1 为真时,才会检查 Conditon2。

让我们检查以下简短示例,就会清楚:

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

ok就可以了

但是,如果我们对 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')

后面的代码给出错误ZeroDivisionError: division by zero ,其中,首先检查 a/b 并且 b 等于 0。

但是,在第一个代码中,条件 b,=0 首先被检查,并给出False ,所以第二个条件a/b>3没有被处理。

所以,这两个说法是不一样的。

暂无
暂无

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

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