【发布时间】:2021-05-23 13:58:37
【问题描述】:
我有一个代码,结果是这样的嵌套字典:
{'weather': {'cloudy': 'yes',
'rainy': {'wind': {'strong': 'no', 'weak': 'yes'}},
'sunny': {'humidity': {'high': 'no', 'normal': 'yes'}}}}
现在我需要将其“展平”为这样的列表列表:
[[weather, cloudy, yes], [weather, rainy, wind, strong, no], [weather, rainy, wind, weak, yes], ...]
我尝试了许多不同的方法来解决这个问题,但就是无法正确解决,有没有人遇到过类似的问题?
编辑:有人要求查看我的一些试验,我尝试通过将它变成一个列表来做这样的事情:
def change(self, tree):
l = []
for key, value in tree.items():
l.append(key)
if type(value) is dict:
l.extend(change(value))
else:
l.append(value)
return l
返回:
['weather', 'cloudy', 'yes', 'rainy', 'wind', 'strong', 'no', 'weak', 'yes', 'sunny', 'humidity', 'high', 'no', 'normal', 'yes']
这不是我需要的,但我不知道如何解决它。
【问题讨论】:
-
你能展示一些你的试验吗?
标签: python python-3.x dictionary tree