gpt4 book ai didi

python - 索引错误: list index out of range error when reversing a list

转载 作者:行者123 更新时间:2023-11-30 21:59:22 24 4
gpt4 key购买 nike

当我输入以下内容时:

def FirstReverse(str): 

# code goes here

x = len(str)

s = list(str)

while x >= 0:
print s[x]
x = x - 1

# keep this function call here
# to see how to enter arguments in Python scroll down
print FirstReverse(raw_input())

我收到此错误

ERROR ::--Traceback (most recent call last):
File "/tmp/105472245/main.py", line 14, in <module>
print FirstReverse("Argument goes here")
File "/tmp/105472245/main.py", line 7, in FirstReverse
print s[x] IndexError: list index out of range

最佳答案

Python 索引从 0 开始。因此,对于字符串“Hello”,索引 0 指向“H”,索引 4 指向“o”。当你这样做时:

x = len(str)

您将 x 设置为 5,而不是最大索引 4。因此,请尝试以下操作:

x = len(str) - 1

另外,还有另一个指针。而不是:

x = x - 1

您可以简单地说:

x -= 1

关于python - 索引错误: list index out of range error when reversing a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com