1

经过大量搜索后遇到了这个例子。

nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
flattened = lambda *n: (e for a in n for e in (flattened(*a) if isinstance(a, (tuple, list)) else (a,)))
print(list(flattened(nested_lists)))

它有效,但丑陋且难以理解,但我喜欢它是在 1 行代码中完成的。

有没有更简洁的方法,同时仍然保持简洁。

谢谢

为了使 ts 清晰,代码应该给出结果 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

4

1 回答 1

0

扁平化嵌套列表的简单方法:

nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
output = []
def reemovNestings(l): 
    for i in l: 
        if type(i) == list: 
            reemovNestings(i) 
        else: 
            output.append(i)

# Driver code 
print ('The original list: ', nested_lists) 
reemovNestings(nested_lists) 
print ('The list after removing nesting: ', output)

输出:

The original list:  [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]                                   
The list after removing nesting:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
于 2020-04-19T15:52:06.847 回答