PythonNote027---嵌套list偏平化操作

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 于南京市江宁区九龙湖

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值