展平任意深度的嵌套列表

Flattening arbitrarily deep nested lists

我想从 Python 中的 n 个嵌套列表中检索数据。即:

[[[[[1, 2]]]]] => [1, 2]

我显然可以做类似的事情:

mylist[0][0][0][0]

但我想知道是否有一种方法可以做到这一点而不必知道列表的嵌套有多深。

我想这样做是因为我从需要处理的 REST API 请求中获得了一些格式相当错误的数据。

您可以使用递归生成器从嵌套列表中生成元素:

from typing import Collection

def check_nested(obj):
    for sub_obj in obj:
        # tuples, lists, dicts, and sets are all Collections
        if isinstance(sub_obj, Collection):
            yield from check_nested(sub_obj)
        else:
            yield sub_obj


l = [[[[[1, 2]]]]]
list(check_nested(l))
[1, 2]

# This will work for other formats
l = [[[[[1, 2]]]], [[3, 4]]]

list(check_nested(l))
[1, 2, 3, 4]

注意事项 typing.Collection

因为这得到了新的赞成票,我想回来纠正一些事情:

from typing import Collection

isinstance('', Collection)
True

这可能会导致意外错误,因此更好的解决方案是实例检查:

def check_nested(obj):
    for sub_obj in obj:
        if isinstance(sub_obj, (list, dict, set, tuple)):
            yield from check_nested(sub_obj)
        else:
            yield sub_obj