gpt4 book ai didi

python - 展平python中的嵌套结构

转载 作者:行者123 更新时间:2023-11-28 21:54:33 31 4
gpt4 key购买 nike

我如何在 Python 中将其展平,以便每个“小部件”都是列表的一个元素?

{  "widgets" :[{"num": "1", "letter": "a",
"widgets" :[{"num": "2", "letter": "b",
"widgets" :[{"num": "3","letter": "c"},
{"num": "4", "letter": "d"}]
}]
}]
}

所以它最终变成了

[{"num":"1", "letter","a"},
{"num": "2", "letter":"b"},
{"num": "3", "letter":"c"},
{"num": "4", "letter":"d"}]

最佳答案

在你射杀了给你数据的人之后,可能是这样的:

def flatten_widgets(widget):
stack = [widget['widgets']]
while stack:
for widget in stack.pop():
yield {k: v for k, v in widget.items() if k != 'widgets'}
if 'widgets' in widget:
stack.append(widget['widgets'])

>>> list(flatten_widgets(a))

[{'letter': 'a', 'num': '1'},
{'letter': 'b', 'num': '2'},
{'letter': 'c', 'num': '3'},
{'letter': 'd', 'num': '4'}]

关于python - 展平python中的嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045543/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com