gpt4 book ai didi

python - 列表索引必须是整数,而不是 str

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:41 24 4
gpt4 key购买 nike

class targil4(object):
def plus():
x=list(raw_input('enter 4 digit Num '))
print x
for i in x:
int(x[i])
x[i]+=1
print x

plus()

这是我的代码,我尝试从用户那里获取 4 位数字的输入,然后将每个数字加 1,然后打印回来。当我运行这段代码时,我得到了按摩:

Traceback (most recent call last):
['1', '2', '3', '4']
File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 1, in <module>
class targil4(object):
File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 10, in targil4
plus()
File "C:/Users/Maymon/PycharmProjects/untitled4/targil4.py", line 6, plus
int(x[i])
TypeError: list indices must be integers, not str

Process finished with exit code 1

最佳答案

我相信您可以通过实际查看每个陈述并了解发生了什么来从此处的答案中获得更多信息。

# Because the user enters '1234', x is a list ['1', '2', '3', '4'],
# each time the loop runs, i gets '1', '2', etc.
for i in x:
# here, x[i] fails because your i value is a string.
# You cannot index an array via a string.
int(x[i])
x[i]+=1

因此我们可以根据我们的新理解调整代码来“修复”这个问题。

# We create a new output variable to hold what we will display to the user
output = ''
for i in x:
output += str(int(i) + 1)
print(output)

关于python - 列表索引必须是整数,而不是 str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577110/

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