python 递归实例(recursion in real world using python)

现有数据,结构如下:

recipes = {
    'apple_pie': {
        'ingredients': ['flour', 'sugar', 'eggs', 'shortening', 'apples', 'cinnamon'],
        'cook_time': 60,
        'prep_time': 30,
        'ratings': {'john': 10, 'emily': 8, 'mom': 4}
    },
    'peanut_butter_cookies': {
        'ingredients': ['flour', 'sugar', 'peanut_butter', 'butter', 'eggs'],
        'cook_time': 45,
        'prep_time': 20,
        'allergens': ['peanuts']
    },
    'clam_chowder': {
        'ingredients': ['flour', 'milk', 'clams', 'vegetable_stock', 'salt'],
        'cook_time': 120,
        'prep_time': 30,
        'allergens': ['shellfish']
    }
}

如果对Python中的基本数据类型--字典类型比较熟悉的话,可以很容易发现这是个“大字典”。而字典里面又包含字典,这样组织数据复合人类的逻辑,但是编程时候需要解析这些数据。比如我们需要解析成这样的数据:

{'apple_pie/cook_time': 60,
 'apple_pie/ingredients': ['flour',
                           'sugar',
                           'eggs',
                           'shortening',
                           'apples',
                           'cinnamon'],
 'apple_pie/prep_time': 30,
 'apple_pie/ratings/emily': 8,
 'apple_pie/ratings/john': 10,
 'apple_pie/ratings/mom': 4,
 'clam_chowder/allergens': ['shellfish'],
 'clam_chowder/cook_time': 120,
 'clam_chowder/ingredients': ['flour',
                              'milk',
                              'clams',
                              'vegetable_stock',
                              'salt'],
 'clam_chowder/prep_time': 30,
 'peanut_butter_cookies/allergens': ['peanuts'],
 'peanut_butter_cookies/cook_time': 45,
 'peanut_butter_cookies/ingredients': ['flour',
                                       'sugar',
                                       'peanut_butter',
                                       'butter',
                                       'eggs'],
 'peanut_butter_cookies/prep_time': 20}
仔细查看数据,发现字典里面不再有小字典。通俗来时就是把里面的大块数据(字典)打碎,然后碾平。

那么我们如何实现这样的解析功能呢?

看来用递归不错哟。


现在使用递归方法将上面的字典数据一层层地”碾平“

def flatten(obj):
    if isinstance(obj, list):
        # if object is a list object, flatten every sub e.ement
        result = []
        for elem in obj:
            flat_elem = flatten(elem)
            result.append(flat_elem)
    elif isinstance(obj, dict):
        # if object is a dictionary, flatten it on level
        result = {}
        for key, value in obj.items():
            if isinstance(value, dict):
                flat_value = flatten(value)
                for subkey, subvalue in flat_value.items():
                    flat_key = '/'.join([key, subkey])
                    result[flat_key] = subvalue
            else:
                result[key] = value
    else:
        # otherwise just return the value
        result = obj

    return result

现在使用递归方法将上面的字典数据一层层地”碾平“

def flatten(obj):
    if isinstance(obj, list):
        # if object is a list object, flatten every sub e.ement
        result = []
        for elem in obj:
            flat_elem = flatten(elem)
            result.append(flat_elem)
    elif isinstance(obj, dict):
        # if object is a dictionary, flatten it on level
        result = {}
        for key, value in obj.items():
            if isinstance(value, dict):
                flat_value = flatten(value)
                for subkey, subvalue in flat_value.items():
                    flat_key = '/'.join([key, subkey])
                    result[flat_key] = subvalue
            else:
                result[key] = value
    else:
        # otherwise just return the value
        result = obj

    return result

输出结果:

你可能感兴趣的:(python 递归实例(recursion in real world using python))