Skip to main content
 首页 » 编程设计

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

2024年10月17日8傻小

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)