好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python进行数组合并的方法

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

假设有a1和a2两个数组:

a1=[1,2,3]

a2=[4,5,6]

合并方式

1. 直接相加

#合并后赋值给新数组a3a3?=?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?-?startprint?cost
?

a1=range(100000000)

a2=range(100000000)

start=time.time()

a1.extend(a2)

new_a?=?a1

end=time.time()

cost?=?end?-?startprint?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?-?startprint?cost

分别输出:

17.2916171551

20.8185400963

55.1758739948

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

博主:测试生财

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

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

博客园:https://HdhCmsTestcnblogs测试数据/qa-freeroad/

51cto:https://blog.51cto测试数据/14900374

?

查看更多关于python进行数组合并的方法的详细内容...

  阅读:42次