0

有下面的一道算法题,使用python实现,一直没有思路,请各位大神给一点思路好么

实现flatten函数,有如下功能:
nested_json = {
        "a": 1,
        "b": [35, 26],
        "c": [{
                "d": [2, 3, 4],
                "e": [
                    {
                        "f": 1,
                        "g": 2
                        }
                    ]
            }],
        "h": {}
        }
    
    flattened_json = flatten(nested_json)
        

    print(flattened_json)
    {'a': 1,
     'b.0': 35,
     'b.1': 26,
     'c.0.d.0': 2,
     'c.0.d.1': 3,
     'c.0.d.2': 4,
     'c.0.e.0.f': 1,
     'c.0.e.0.g': 2,
     'h': {}
    }
扬帆 22
2019-05-29 提问
3 个回答
0

已采纳

这道题不是考算法,而是考个人对python各种语法、函数的熟悉程度

# coding: utf-8
# __author__: 'Rich'

from __future__ import unicode_literals


def flatten(d, parent_key=None, out={}):
    for k, v in d.items():
        if not isinstance(v, list):
            key = '{}.{}'.format(parent_key, k) if parent_key else k
            out[key] = v
            continue

        for i, v1 in enumerate(v):
            key = '{}.{}.{}'.format(parent_key, k, i) if parent_key else '{}.{}'.format(k, i)
            if not isinstance(v1, dict):
                out[key] = v1
                continue

            flatten(v1, key, out)

    return out


nested_json = {
    "a": 1,
    "b": [35, 26],
    "c": [{
            "d": [2, 3, 4],
            "e": [
                {
                    "f": 1,
                    "g": 2
                    }
                ]
        }],
    "h": {}
}

flattened_json = flatten(nested_json)
print(flattened_json)
0

麻烦可以详细说一下你的需求吗?

0

供参考.

代码:

#!/usr/bin/env python

from collections import namedtuple
from collections.abc import Iterable

Node = namedtuple("Node", ["keys", "value"])
Node.__new__.__defaults__ = ((), None)

def flattern(nested):
    def dfs(node):
        ks, nv = node
        if nv and isinstance(nv, Iterable):
            if type(nv) == list:
                kvs = enumerate(nv)
            elif type(nv) == dict:
                kvs = nv.items()
            for k, v in kvs:
                n = Node(keys=ks+(str(k),), value=v)
                yield from dfs(n)
        else:
            yield node

    root = Node(keys=(), value=nested)
    return {'.'.join(keys):value for keys, value in dfs(root)}

撰写答案

推广链接