简体   繁体   English

Python - 收集递归 function 的 output

[英]Python - collect output of recursive function

I have written a function designed to flatten a json.我写了一个 function 设计来压平 json。 The function works recursively - if a key, value pair's value is not a json, the key,value pair is returned, otherwise, the function is called again on the value: function 递归工作 - 如果键值对的值不是json,则返回键值对,否则,将在值上再次调用 function:

def flatten_json(j):
    for k, v in j.items():
        if isinstance(v, dict):
            flatten_json(v)
        else:
            yield (k,v)

flat_json = {x[0]: x[1] for x in flatten_json(j)}

The idea being that whenever the function yield sa tuple, it is collected into the flat_json dict.这个想法是每当 function yield一个元组时,它就会被收集到 flat_json 字典中。 As it stands, nested outputs are ignored - only the top level key, value pairs appear in flat_json.就目前而言,嵌套输出被忽略 - 只有顶级键值对出现在 flat_json 中。

This is exactly what yield from is for:), to yield elements one by one from calling a generator from within a generator (whether that is a recursive call or not).这正是yield from的用途:),通过从生成器内部调用生成器(无论是否是递归调用)来逐个生成元素。

try:尝试:

def flatten_json(j):
    for k, v in j.items():
        if isinstance(v, dict):
            yield from flatten_json(v)
        else:
            yield (k,v)


j = {'foo': 'bar', 'foo1': 'bar1', 'nest1': {'foo2': 'bar2'}}
flat_json = {x[0]: x[1] for x in flatten_json(j)}
print(flat_json)

Output: Output:

{'foo': 'bar', 'foo1': 'bar1', 'foo2': 'bar2'}

running example here: https://ideone.com/Z5aO9V此处运行示例: https://ideone.com/Z5aO9V

Yield it like the normal data:像正常数据一样产生它:

yield (k, flatten_json(v))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM