list indices必须是整数,而不是str

时间:2016-09-19 15:45:25

标签: python string list integer indices

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

2 个答案:

答案 0 :(得分: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

所以我们可以修复&#34;通过我们的新理解来调整代码。

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

答案 1 :(得分:0)

您也可以使用list comprehension并执行

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