zoukankan      html  css  js  c++  java
  • 多维列表(元组)碾成一维形式

    一.需求

      原格式:

    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
  • 相关阅读:
    linux报错-bash: ./xx.sh: Permission denied
    shell脚本报错:-bash: xxx: /bin/bash^M: bad interpreter: No such file or directory
    点灯
    笑话
    bzoj 4898: [Apio2017]商旅
    bzoj 4446: [Scoi2015]小凸玩密室
    bzoj 4237: 稻草人
    idea
    springmvc集成swagger实现接口文档自动化生成
    基本的内存泄漏的解释
  • 原文地址:https://www.cnblogs.com/tjp40922/p/11321547.html
Copyright © 2011-2022 走看看