首页 > 编程语言 > 详细

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

时间:2017-02-07 15:05:44      阅读:152      评论:0      收藏:0      [点我收藏+]

今天在生成数据的时候遇到了这个需求,其实写一个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

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

原文:http://www.cnblogs.com/piperck/p/6373947.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!