多维列表(元组)碾成一维形式

一.需求

  原格式:

input=[[1,2,3],[4,5,6],[7,8,9]]

  目标格式:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

二.方法

  1.sum函数合并

input=[[1,2,3],[4,5,6],[7,8,9]]
output=sum(input,[])
print(output)

#结果:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

  这个看上去很简洁,不过有类似字符串累加的性能陷阱。

  2.reduce函数

from functools import reduce

input=[[1,2,3],[4,5,6],[7,8,9]]
output=reduce(list.__add__, input)
print(output)

#结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]

  做序列的累加操作。也是有累加的性能陷阱。

  3.列表推导式

input=[[1,2,3],[4,5,6],[7,8,9]]
output=[item for sublist in input for item in sublist]
print(output)

#结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]

  列表推导式,看着有些长,而且还要for循环两次,变成一行理解需要费劲一些,没有那么直观

  4.itertools 类库

import itertools
input=[[1,2,3],[4,5,6],[7,8,9]]
ouput=list(itertools.chain(*input))
print(ouput)

#结果
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 三.性能对比

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 51.2 usec per loop

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(list.__add__,l)'
1000 loops, best of 3: 572 usec per loop
 
python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 545 usec per loop

python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99; import itertools;' 'list(itertools.chain(*l))'
10000 loops, best of 3: 35.1 usec per loop

 

转载于:https://www.cnblogs.com/tjp40922/p/11321547.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值