我在访问这样的字典 AS 项目时遇到问题:
def T():
AS = {"fen": {'used': 0, 'to_end': None, 'depth': 1, 'type': 'normal'}}
return {fen: (data['to_end'], data['type']) for fen, data in AS.items() if data['to_end'] is not True}
s = "fen"
AS = T()
if s in AS and AS[s]['used'] == 0:
print(AS)
给出了这个错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[37], line 7
4 s = "fen"
5 AS = T()
----> 7 if s in AS and AS[s]['used'] == 0:
8 # Tisk hodnot
9 print(AS)
TypeError: tuple indices must be integers or slices, not str
我知道一种解决方法,但我希望详细了解这种方法失败的原因。(以及如何以最小的努力修复它)
在 T() 函数中,您返回一个字典,其中值是元组,而不是字典。当您尝试访问 AS[s]['used'] 时,您正在尝试在元组上使用字符串索引,这是不可能的 - 因此会出现错误“元组索引必须是整数或切片,而不是 str”。
这是代码片段的稍微修改版本。
def T():
AS = {"fen": {'used': 0, 'to_end': None, 'depth': 1, 'type': 'normal'}}
return {fen: data for fen, data in AS.items() if data['to_end'] is not None}
s = "fen"
AS = T()
if s in AS and AS[s]['used'] == 0:
print(AS)