python 平摊列表

>>> a = [[1, 2], [3, 4], [5, 6]]

>>> import itertools

>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]
 
>>> sum(a, [])
[1, 2, 3, 4, 5, 6]
 
>>> [x for l in a for x in l]
[1, 2, 3, 4, 5, 6]
 
>>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> [x for l1 in a for l2 in l1 for x in l2]
[1, 2, 3, 4, 5, 6, 7, 8]
 
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8]
 
注意: 根据Python的文档,itertools.chain.from_iterable是首选。
原文地址:https://www.cnblogs.com/WhatTTEver/p/6942746.html