列表索引必须是整数或片,而不是字符串

2024-05-14 21:19:45 发布

您现在位置:Python中文网/ 问答频道 /正文

@classmethod
def RoundToValidQuantity(cls, symbol_data, desired_quantity, round_up: bool = False) -> Decimal:
    """ Returns the minimum quantity of a symbol we can buy,
    closest to desiredPrice """

    lot_filter = {}

    for fil in symbol_data["filters"]:
        if fil["filterType"] == "LOT_SIZE":
            lot_filter = fil
            break

TypeError:列表索引必须是整数或片,而不是str

我需要你的帮助


Tags: falsedatadeffiltersymbolquantityclsbool
1条回答
网友
1楼 · 发布于 2024-05-14 21:19:45

我假设您的列表由数字和非数字组成。在Python中,只能通过提供整数索引直接访问列表

要避免此问题,请使用enumerate()函数。这提供了一个元组列表,其中包含您的值和可用于访问列表的索引

list = [1, 2, "a", "b", 3, 4, "c", "d"]

for index, value in enumerate(list):
  print("the index is: " + index)
  print("the value is: " + value)

预期产出:

the index is: 0
the value is: 1

the index is: 1
the value is: 2

the index is: 2
the value is: a

the index is: 3
the value is b

等等

编辑:

如果您使用的是词典,则必须使用大括号声明:

>>> my_dict = {}

然后,您可以向其中添加字段,如下所示:

>>> my_dict["field_name"] = "blah"

然后像这样访问它:

>>> my_dict["field_name"]
'blah'

相关问题 更多 >

    热门问题