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 shell 常用命令记录
    [Bat]批量重命名文件
    【转】java术语(PO/POJO/VO/BO/DAO/DTO)
    TesseractOCR3.0语言库训练步骤
    关于Delphi Rtti对应TDatetime的一些启示
    Ubuntu Server 12.04 安装mysql 5.6.10
    Delphi透明 圆角 窗体 【转】
    奇怪的~用法
    很有用的VS2005插件——SlickEdit
    还不习惯Office 2007
  • 原文地址:https://www.cnblogs.com/tjp40922/p/11321547.html
Copyright © 2011-2022 走看看