zoukankan      html  css  js  c++  java
  • python进行数组合并的方法

    python的数组合并在算法题中用到特别多,这里简单总结一下:

    假设有a1和a2两个数组:

    a1=[1,2,3]

    a2=[4,5,6]

    合并方式

    1. 直接相加

    #合并后赋值给新数组a3
    a3 = a1 + a2

    2. extend

    #调用此方法,a1会扩展成a1和a2的内容
    a1.extend(a2) 

    3. 列表表达式

    #先生成新的二维数组
    a3 = [a1, a2]
    #列表推导形成新的数组
    a4 = [ y for a in a3 for y in a ]

    合并性能

    下面分别测试下三种数组合并方式的性能

    import time
    
    a1=range(100000000)
    
    a2=range(100000000)
    
    start=time.time()
    
    new_a = a1 + a2
    
    end=time.time()
    
    cost = end - start
    
    print cost
     
    
    a1=range(100000000)
    
    a2=range(100000000)
    
    start=time.time()
    
    a1.extend(a2)
    
    new_a = a1
    
    end=time.time()
    
    cost = end - start
    
    print cost
    
     
    
    a1=range(100000000)
    
    a2=range(100000000)
    
    a3=[a1,a2]
    
    start=time.time()
    
    new_a = [ y for a in a3 for y in a ]
    
    end=time.time()
    
    cost = end - start
    
    print cost

    分别输出:

    17.2916171551

    20.8185400963

    55.1758739948

    可以看出:在数据量大的时候,第一种方式的性能要高出很多。

    博主:测试生财

    座右铭:专注测试与自动化,致力提高研发效能;通过测试精进完成原始积累,通过读书理财奔向财务自由。

    csdn:https://blog.csdn.net/ccgshigao

    博客园:https://www.cnblogs.com/qa-freeroad/

    51cto:https://blog.51cto.com/14900374

  • 相关阅读:
    Lesson_strange_words6
    Lesson_strange_words3
    Lesson_strange_words4
    Lesson_strange_words1
    Lesson_strange_words2
    关于我们子页面
    关于我们页面
    走进龙门石窟子页面
    3.用户登陆注册
    2.项目初始化
  • 原文地址:https://www.cnblogs.com/qa-freeroad/p/14131440.html
Copyright © 2011-2022 走看看