简体   繁体   English

这个递归 Python 代码是如何工作的?

[英]How does this recursive Python code work?

I came across this recursive function that's supposed flatten a dictionary:我遇到了这个递归的 function ,它应该使字典变平:

def flatten(data, prefix='', separator='.'):
    """Flattens a nested dict structure. """
    if not isinstance(data, dict):
        return {prefix: data} if prefix else data

        result = {}
        for (key, value) in data.items():
            result.update(flatten(value,_get_new_prefix(prefix, key, separator),
            separator=separator))
        return result

def _get_new_prefix(prefix, key, separator):
    return (separator.join((prefix, str(key))) if prefix else str(key))

it's also supposed to be fed with this data:它也应该被输入这些数据:

nested = {
 'fullname': 'Alessandra',
 'age': 41,
 'phone-numbers': ['+447421234567', '+447423456789'],
 'residence': {'address': {'first-line': 'Alexandra Rd','second-line': '',},
 'zip': 'N8 0PP',
 'city': 'London',
 'country': 'UK',
 },
}

I'm trying to figure out how it works and particularly how the "prefix" parameter works and in what case it will not be empty.我试图弄清楚它是如何工作的,特别是“前缀”参数是如何工作的,在什么情况下它不会为空。

The flatten() function builds the path down the tree, where the names in the path are separated by the separator. flatten() function 沿着树构建路径,其中路径中的名称由分隔符分隔。 The prefix is added to the beginning of that path.前缀被添加到该路径的开头。

prefix is only "empty" if you set it to None .如果您将其设置为None ,则prefix仅是“空的”。 That will have the effect of suppressing the prefix.这将具有抑制前缀的效果。

For example, compare the output of this:例如,比较这个的 output:

[print(k, ' = ', v) for k,v in flatten(nested, prefix='xxx', separator='/').items()]

...with this: ...有了这个:

[print(k, ' = ', v) for k,v in flatten(nested, prefix=None).items()]

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

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