gpt4 book ai didi

python - 将字典展平为格式化字符串

转载 作者:行者123 更新时间:2023-12-04 13:31:43 25 4
gpt4 key购买 nike

我被这个问题困了很长时间。
假设我们有一个 Python 字典,如下所示:

d = {'TOP': [{'S': [{'NP-TMP': [{'NP': [{'DT': ['This']}, {'NN': ['time']}]},
{'ADVP': [{'RP': ['around']}]}]},
{'NP-SBJ': [{'PRP': ['they']}]},
{'VP': [{'VBP': ["'re"]},
{'VP': [{'VBG': ['moving']},
{'ADVP': [{'RB': ['even']},
{'RBR': ['faster']}]}]}]}]}]}
我想将其转换为以下格式:
(((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))
我尝试了以下代码,但无法继续进行。
for tree in d.values():
for i, j in tree[0].items():
for n in j:
for p in n.items():
print(p)

最佳答案

递归生成器可以工作(虽然不是很好……)

def sub(dct):
for lst in dct.values():
for item in lst:
if isinstance(item, str):
yield f"{item}"
elif isinstance(item, dict):
yield "("
yield from sub(item)
yield ")"
elif isinstance(item, list):
assert len(item) == 1
yield f"{item[0]}"
else:
pass
结果是:
r = f"({''.join(sub(d))})"
print(r)
# (((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))

关于python - 将字典展平为格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64694024/

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