将大数组里面的小数组平行展开的实现(Making a flat list out of list of lists in Python)...

今天在生成数据的时候遇到了这个需求,其实写一个for循环可以很容易解决这个问题,但是无论是性能还是酷炫程度上都不行 所以顺手搜索了一下。

例子是将

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

变成

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

 

plan1: 使用列表推导式

print [item for i in l for item in i]

plan2: 使用reduce

print reduce(lambda x, y: x + y, l)
print reduce(operator.concat, l)

plan3: 使用itertool

print list(itertools.chain.from_iterable(l))

plan4: 使用sum

print sum(l, [])

那么,哪种方法最快呢? timeit!

import timeit


print timeit.timeit('reduce(lambda x, y: x + y, l)', setup='l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]', number=10000)
print timeit.timeit('reduce(operator.concat, l)', setup='import operator;'
                                                        'l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]', number=10000)
print timeit.timeit('[item for i in l for item in i]', setup='l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]', number=10000)
print timeit.timeit('list(itertools.chain.from_iterable(l))', setup='import itertools;'
                                                                    'l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]', number=10000)
print timeit.timeit('sum(l, [])', setup='l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]', number=10000)

output:

0.0129590034485
0.00949192047119
0.0104038715363
0.0122821331024
0.0097348690033

可以看到,速度其实都差不多,在一个数量级上,但是第二个操作一般会更快 也就是使用operator的operator.concat

 

 

Reference:

http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python

http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python

转载于:https://www.cnblogs.com/piperck/p/6373947.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值