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]
[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]
[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
list(flatten(x_list))
[0, 1, 2, 3, 4, 5, 6]