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

list indices must be integers, not str

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

您也可以使用 list comprehension

y = [int(i) + 1 for i in x]
print y

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

# 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

所以我们可以"fix"通过我们新的理解来调整代码。

# 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)