Intro
嵌套list扁平化,把每个子元素取出来,再拉平,放到一个list中。R中有unlist方法,Scala中有flatMap方法,python中也可类似实现。直接看case。
方法一
x_list = [[0,1],[2,3],[4,5,6]]
flat_list = [item for sublist in x_list for item in sublist]
flat_list
[0, 1, 2, 3, 4, 5, 6]
这个用法也会加上if判断,举个例子,把偶数元素提取出来
y_list = [1,2,3,4,5]
even_list = [i for i in y_list if i%2==0]
even_list
[2, 4]
方法二
import functools
import operator
functools.reduce(operator.iconcat, x_list, [])
[0, 1, 2, 3, 4, 5, 6]
方法三
functools.reduce(lambda x,y: x+y,x_list)
[0, 1, 2, 3, 4, 5, 6]
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
functools.reduce(lambda x,y: x+y,list(range(5)))
10
方法二、三都是利用了reduce函数,传入两个参数(function, sequence)。
- 第一次计算时,向function中传入sequence的第一个和第二个元素,得出计算结果res1
- 后面每次计算,传入上一步计算结果和sequence中最近一个未参与计算的元素
方法四
from pandas.core.common import flatten
list(flatten(x_list))
[0, 1, 2, 3, 4, 5, 6]
Ref
[1] https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists
2021-03-16 于南京市江宁区九龙湖