繁体   English   中英

TypeError 的问题:列表索引必须是整数或切片,而不是 dict

[英]Issue with TypeError: list indices must be integers or slices, not dict

对于下面的代码片段,我收到错误: TypeError: list indices must be integers or slices, not dict

coin['orderBooks'][i]确实是一个字典,但我怎样才能删除/删除它呢? 我需要从我的数据集中删除以进行进一步分析。

#check if bid_price or ask_price exists, if not remove it from orderbooks
for coin in orderbooks:
    for i in coin['orderBooks']:
        bid_price = i['orderBook']['bids']
        ask_price = i['orderBook']['asks']
        if bid_price == [] or ask_price == []:
            del coin['orderBooks'][i]
Traceback (most recent call last):

  File "<ipython-input-47-07d8008d3d9c>", line 6, in <module>
    del coin['orderBooks'][i]

TypeError: list indices must be integers or slices, not dict

你误会了, coin['orderBooks'][i]不是一个dict (它甚至会抛出错误), i是一个错误,你应该以不同的方式命名它,因为你访问i['orderBook']你看到这是一个字典,要删除它,您可以使用它在数组中的索引

它会像:

for coin in orderbooks:
    for idx, val in enumerate(coin['orderBooks']):
        bid_price = val['orderBook']['bids']
        ask_price = val['orderBook']['asks']
        if not bid_price or not ask_price:
            del coin['orderBooks'][idx]

但是由于迭代时删除不是一个好主意,你可以保留好的,循环理解很容易

for coin in orderbooks:
    coin['orderBooks'] = [val for val in coin['orderBooks'] 
                              if val['orderBook']['bids'] and val['orderBook']['askas']]

您也可以直接使用其 bool 值( bool([]) == False )检查空列表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM