zoukankan      html  css  js  c++  java
  • 将大数组里面的小数组平行展开的实现(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

  • 相关阅读:
    PowerDesigner通过SQL文件,反向生成模型
    跨域请求设置
    SSO单点登录与登出
    jwt使用
    git概念理解
    Slf4j MDC机制
    ASP.NET Core依赖注入最佳实践,提示&技巧
    EFCore数据库迁移命令整理
    RSA加密的使用
    CocoaPods 安装的第三方删除
  • 原文地址:https://www.cnblogs.com/piperck/p/6373947.html
Copyright © 2011-2022 走看看