列表索引必须是整数或切片,而不是 str - Python

List indices must be integers or slices, not str - Python

我正在使用字典来编译有关股票等的数据,但是当我引用用户输入的 gtin 代码时,出现错误 'List indices must be integers or slices, not 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 作为唯一元素的列表,因此很明显它不能被索引 [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'] 吗?