多个列表合并、嵌套列表合并的操作
多个列表合并
多个列表合并时常规操作,不提
x = [0,1]
y = [2,3]
[*x,*y]
[0, 1, 2, 3]
x+y
[0, 1, 2, 3]
嵌套列表打平
import operator
from functools import reduce
a = [[1,2,3], [4,5,6], [7,8,9]]
reduce(operator.add, a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
或者
reduce(lambda x,y:x+y, a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
多层嵌套的操作,即子元素可能是list
可以想到用递归操作
def flat(l):
for item in l:
if not isinstance(item, (list, tuple)):
yield item
else:
yield from flat(item)
a = [[1,2,3], 4,5,6, [7,8,9]]
list(flat(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Ref
[1] https://www.zhihu.com/question/27010691
2022-04-02 于南京市江宁区九龙湖