将具有多层嵌套列表的不规则列表转换为列表列表

Convert an irregular list with multiple levels of nested lists to a list of lists

我有一些数据位于一个包含许多不同(子)级别的杂乱嵌套列表中。我并不真正关心这些级别,只想在一个大列表列表中获取数据。

我已经在寻找如何展平列表列表或嵌套列表(例如here, here and here),但这些问题的解决方案不适用于此处(我认为)。

所以基本上我需要的是:

nested_list = [[[1, 2, 3], [[5, 6, 7], [8, 9, 10, 11, 23]]], [4], [[12, 13, 14], [[15, 16], [[17, 18], [19, 20]]]], [21, 22, 25, 26]]
unnested_list = nested_to_listoflist( nested_list )
#=> [ [1, 2, 3], [5, 6, 7], [8, 9, 10, 11, 23], [4], [12, 13, 14], [15, 16], [17, 18], [19, 20], [21, 22, 25, 26] ]

有什么建议吗?

我认为这会为你完成工作,

open_ = []
open_.append(nested_list)
res = []
while len(open_) > 0:
    element = open_.pop()
    for item in element:
        if isinstance(item, list):
            open_.append(item)
        else:
            res.append(element)
            break

一种有趣的做法(不推荐):

l = str(nested_l)
inner = False
new_l = "["

for i in range(2,len(l)):
    if l[i] == "]" and inner:
        inner = False
    elif l[i] == "[" and not inner:
        inner = True
    elif l[i] == "[" and inner or l[i] == "]" and not inner:
        continue
    new_l+=l[i]

new_l += "]"
new_l = eval(new_l)

向生成器函数 flatten 传递一个列表并查看每个子列表。如果子列表的长度为 0 或者子列表的第一个元素不是另一个列表,它只生成子列表作为要添加到结果中的下一个列表。否则它递归地处理子列表。函数 nested_to_listoflist 只是将所有 "yielded" 列表组合成一个最终列表。

def flatten(l):
    for el in l:
        if not el or not isinstance(el[0], list):
            yield el
        else:
            yield from flatten(el)

def nested_to_listoflist(l):
    return [el for el in flatten(l)]
    # or return list(flatten(l))


nested_list = [[[1, 2, 3], [[5, 6, 7], [8, 9, 10, 11, 23]]], [4], [[12, 13, 14], [[15, 16], [[17, 18], [19, 20]]]], [21, 22, 25, 26]]
unnested_list = nested_to_listoflist(nested_list)
print(unnested_list)

打印:

[[1, 2, 3], [5, 6, 7], [8, 9, 10, 11, 23], [4], [12, 13, 14], [15, 16], [17, 18], [19, 20], [21, 22, 25, 26]]

Python Demo

试试这个:

def nested_to_listoflist(nested_list):
    if len(nested_list) == 0 or not isinstance(nested_list[0], list):
        return [nested_list]

    unnested_list = []
    for l in nested_list:
        unnested_list += nested_to_listoflist(l)

    return unnested_list

你可以使用这个递归算法:

def flatten(l):
    result = []
    for item in l:
        if isinstance(item,list):
            if len(item)>0 and isinstance(item[0], list):
                result.extend(flatten(item))  #  recursion
            else:             
                result.append(item)
        else:
            result.append([item])   # decide what to do with stand_alone integers
    return result

nested_list = [[[1, 2, 3], [[5, 6, 7], [8, 9, 10, 11, 23]]], [], [[12, 13, 14], [[15, 16], [[17, 18], [19, 20]]]], [21, 22, 25, 26],3]
flattened_list = flatten(nested_list)

#  [[1, 2, 3], [5, 6, 7], [8, 9, 10, 11, 23], [], [12, 13, 14], [15, 16], [17, 18], [19, 20], [21, 22, 25, 26], [3]]