为什么会出现 IndexError:字符串索引超出范围?
list = (input('Enter your list(number only) : '))
def scorefunction(score):
length = int(len(list))
maxs = length + 1
test = 0
n = 0
while test < maxs:
if list[n+1]<list[n]:
scorefinal = score
n = n + 1
test = test + 1
else:
scorefinal = score + 1
n = n + 1
test = test + 1
return scorefinal
print(scorefunction(0))
我正在尝试创建一个函数,用来比较一个数字和它前面的数字。如果这个数字比前面的数字小,我们就得一分。举个例子:5823。
在这个例子中,我们得一分,因为8大于5,而其他的数字都是小于前面的数字,比如2小于8,3小于2。
2 个回答
0
你的代码有几个问题:
- 你用了“list”这个变量名,但在Python中“list”是一个内置的关键字。所以你应该换个名字。
- 通过input()输入的数据会被当作一个整体的字符串。要把它转换成数字列表,你需要先把这个字符串分开,然后把每个部分转换成整数。
- 在while循环中,你比较列表的元素,但如果使用的索引n+1超过了列表的长度,就会出错。
这是调整过的代码版本:
your_input = input('Enter your list (numbers only) : ')
your_input = [int(num) for num in your_input]
def scorefunction(score):
length = len(your_input)
maxs = length - 1
test = 0
n = 0
scorefinal = score
while n < maxs:
if your_input[n+1] < your_input[n]:
scorefinal = score
else:
scorefinal = score + 1
n += 1
test += 1
return scorefinal
print(scorefunction(0))
不过要注意,3比2大。这个函数会在你输入的数字中,只要有一个数字比后面的数字小,就会返回1。如果你的输入中有多个这样的组合,得分会保持在1。不过,如果得分需要表示这样的组合数量,就得相应地调整。
0
首先,3并不小于2,所以5823的分数应该是2。:D
问题和解释
关于你的问题,答案是maxs = length + 1
这个地方出错了。我不明白你为什么要用变量length
(还有为什么要把它转成int
,因为len()
本来就会返回一个int
)。不过length
其实是等于len(list)
,这里的list
就是你的字符串。
你的变量test
和n
是多余的,所以我们可以把循环条件中的test
换成n
。这样你就能看到你在访问list[n]
,而n
应该小于maxs
。所以n
的最大值就是len(list)
,这会导致越界问题(就像IndexError: string index out of range
所显示的那样)。
在Python中,字符串是字符的数组。而长度为n
的数组的索引是从0
到n-1
。如果你试图访问索引为n
的元素,就会出现IndexError
。
如何解决这个问题
去掉maxs
变量,把它出现的地方换成length
(而length
本身也可以用len(list)
替代)。这样就能解决IndexError
的问题。
另外(这和你的问题无关)考虑去掉test
或n
中的一个,因为它们是多余的。