【问题标题】:list indices must be integers, not str列表索引必须是整数,而不是 str
【发布时间】:2017-01-27 09:01:09
【问题描述】:
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

【问题讨论】:

  • i 已经是您列表中的每个值。做x[i] 是不正确的利用打印出循环中发生的事情来进一步理解,并重新审视循环的课程计划。

标签: python string list integer indices


【解决方案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)

【讨论】:

  • @idjaw 很好。这就是我匆忙写作的结果。 :-) 谢谢!
【解决方案2】:

你也可以使用list comprehension

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

【讨论】:

  • @idjaw 哎呀,我一定是把它命名错了有一段时间了,多么尴尬……谢谢你纠正我
猜你喜欢
  • 2016-02-09
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-09
  • 2016-07-20
  • 1970-01-01
相关资源
最近更新 更多