【问题标题】:List indices must be integers or slices, not str - Python列表索引必须是整数或切片,而不是 str - Python
【发布时间】:2017-10-09 13:19:43
【问题描述】:

我正在使用字典来编译有关股票等的数据,但是当我引用用户输入的 gtin 代码时,我收到错误“列表索引必须是整数或切片,而不是 str - Python”

这是导致此问题的唯一代码部分:

tempStockLvl = [num]['STOCK_LEVEL']  # This is the line the error references
tempStockLvl = int(tempStockLvl)
tempStockLvl = tempStockLvl - quantity
stock[num]['STOCK_LEVEL'] = tempStockLvl

错误:

File "E:\Computer Science\CODE FINAL v2.py", line 206, in subtractQuant tempStockLvl = [num]['STOCK_LEVEL'] TypeError: list indices must be integers or slices, not str

提前感谢任何回答的人:D

【问题讨论】:

  • num 的值是多少?
  • 这是一个八位数字,即 12345670(GTIN 代码)
  • [num]['STOCK_LEVEL'] - 您是否试图索引某种嵌套数据结构? something[num]['STOCK_LEVEL']?
  • 另外,您发布的代码显然与错误消息的来源代码不同。
  • 同样的问题:对象丢失(可能只是stock)。

标签: python string dictionary integer indices


【解决方案1】:

您正在创建一个以 num 作为唯一元素的 List,因此很明显它不能被 index [0] 以外的任何东西访问。

>>> num = 123
>>> l = [num]
>>> l
[123]
>>> l[0]
123
>>> [123]['anything']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>>

你的意思是写tempStockLvl = stock[num]['STOCK_LEVEL']吗?

【讨论】:

  • 它不是一个列表,它引用了一个字典(或试图)
  • @Heather 你知道accepting an answer吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 2020-05-14
  • 2020-11-21
  • 2017-10-08
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多