【问题标题】:Improve flatten function in python改进python中的flatten功能
【发布时间】:2017-01-01 16:31:32
【问题描述】:

给定的功能需要一些改进:

def flatten(d, parent_key=''):
    items = []
    for k, v in d.items():
        try:
            items.extend(flatten(v, '%s%s.' % (parent_key, k)).items())
        except AttributeError:
            items.append(('%s%s' % (parent_key, k), v))
    return dict(items)

我想修改上层函数。
它还使列表变平:

{'d': [1, 2, 3]}

这样的:

{'d[0]': 1, 'd[1]': 3, 'd[2]': 3}

编辑: 这段代码为我做了,但它不像第一个那么圆滑,有什么改进的想法吗?

def flatten_dict(d):
    def items():
        for key, value in d.items():
            if isinstance(value, dict):
                for subkey, subvalue in flatten_dict(value).items():
                    yield key + "." + subkey, subvalue
            elif isinstance(value, list):
                for index, val in enumerate(value):
                    yield key + "[" + str(index) + "]" , value[index]
            else:
                yield key, value

    return dict(items())

【问题讨论】:

    标签: python list dictionary flatten


    【解决方案1】:

    试试这个,

    def flattern(dict_):
        result = {}
        for key in dict_:
            for i,j in enumerate(dict_[key]):
                result[key+'['+str(i)+']'] = j
        return result
    

    这样调用函数,

    In [40]: d
    Out[40]: {'a': [1, 2, 3, 7], 'd': [1, 2, 3]}
    
    In [41]: flattern(d)
    Out[41]: {'a[0]': 1, 'a[1]': 2, 'a[2]': 3, 'a[3]': 7, 'd[0]': 1, 'd[1]': 2, 'd[2]': 3}
    

    【讨论】:

    • 如何将它实现到函数中?
    • 问题是我事先不知道密钥:s
    • 对我不起作用 TypeError: 'int' object is not iterable
    • @Skeec 在哪一行?
    • in this for i,j in enumerate(dict_[key]):
    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 2013-03-14
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多