我在Python中使用字典,经常遇到这样的问题:“列表索引必须是整数或切片,而不是str”该怎么办?

问题描述 投票:0回答:1
>>> d = {'year':[{'season':['winter',['spring']]}]}
>>> d['year']['season']['winter']
Traceback (most recent call last):
  File "<python-input-2>", line 2, in <module>
    d['year']['season']['winter']
    ~~~~~~~~~^^^^^^^^^^
TypeError: list indices must be integers or slices, not str

我尝试更改变量的名称,但没有任何作用。我需要做什么才能“拔出”“弹簧”?

python string dictionary key
1个回答
0
投票

year
的值是一个列表,所以需要对列表进行索引。 一步一步来吧:

>>> d = {'year':[{'season':['winter',['spring']]}]}
>>> d['year']  # result is list
[{'season': ['winter', ['spring']]}]
>>> d['year'][0]  # result is dict
{'season': ['winter', ['spring']]}
>>> d['year'][0]['season']  # result is list
['winter', ['spring']]
>>> d['year'][0]['season'][1]  # result is another list
['spring']
>>> d['year'][0]['season'][1][0]  # result is string
'spring'
© www.soinside.com 2019 - 2024. All rights reserved.