【问题标题】:Reducing nested lists, a function to extend or append lists减少嵌套列表,扩展或追加列表的功能
【发布时间】:2014-09-20 09:54:36
【问题描述】:

我的问题有两个。首先,Python 中有没有一种方法可以减少 JSON 对象/列表中的冗余嵌套?举个简单的例子,它的行为方式如下:

In [1]: reducer([1])
Out[1]: [1]
In [2]: reducer([[[1]]])
Out[2]: [1]
In [3]: reducer({"menu": {"header": "menu", "items": [[{"id": 81}]]}})
Out[3]: {"menu": {"header": "menu", "items": [{"id": 81}]}}

第二,python中有没有原生的extend_or_append函数?该函数的行为如下:

In [1]: tt = []
In [2]: extend_or_append(tt,1)
Out[2]: [1]
In [3]: extend_or_append(tt,[2,3,4,5])
Out[3]: [1,2,3,4,5]

如果此功能不存在,有什么可靠的方法来实现它?

【问题讨论】:

    标签: python json list append extend


    【解决方案1】:

    你的第二个问题是微不足道的。

    def extend_or_append(this, that):
        if isinstance(that, list):
            this.extend(that)
        else:
            this.append(that)
        return this
    

    第一个有点棘手

    def flatten(l):
        for el in l:
            if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
                for sub in flatten(el):
                    yield sub
            else:
                yield el
    
    res = list(flatten([[[[[1]]]]]))
    

    【讨论】:

    • 请注意,basestring 已在 3.x 中消失,因此您需要同时检查 str 和 bytes。
    • 感谢您的回复雅各布。第二个功能通常不起作用。例如,它不会减少以下对象{"menu": {"header": "menu", "items": [[{"id": 81}]]}}。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 2011-08-25
    • 2015-01-10
    • 2012-04-11
    相关资源
    最近更新 更多