python原生list数组与numpy的array
在python中存储集合数据可以选择多种原生数据类型,包括list,array,tuple,dictionary四种类型.其中list可变性强,可存储任意内容并且可变,应用范围广泛.而在进行科学运算,存储纯数字时,numpy被广泛应用,可以说基本完全替代了list.那么它们之间有何不同,差距到底有多大,实际过程中应该如何应用呢?
当然,使用实际案例最能说明问题.
不过这里的测试更适合看成“入门级微基准示例”,而不是放之四海而皆准的性能结论。真正的差距还会受到数据规模、数据类型以及是否使用向量化操作影响。
运算速度比较
简单的加减乘除,以10000内的数字做个比较.
首先是求和
mylist = []
for i in range(1,10001):
mylist.append(i)
# list
from time import time
start = time()
total=sum(mylist)
print(total)
end = time()
print(f"total:{end-start}s")
## 50005000
## total:0.0003197193145751953s
# numpy np.sum
import numpy as np
myarray = np.array(mylist)
start = time()
total = np.sum(myarray)
print(total)
end = time()
print(f"total:{end-start}s")
## 50005000
## total:0.00041031837463378906s
# numpy sum
start = time()
total = sum(myarray)
print(total)
end = time()
print(f"total:{end-start}s")
## 50005000
## total:0.0012726783752441406s
可以看到,在使用求和时原生的数组求和时间为0.0003,而使用numpy的np.sum却需要0.0004,采用内置的sum求numpy中array的和时耗时最久,为0.001,差不多两倍的时间了.而这还不包括将list转换为array的时间,可见在求和上内置的list明显占据上风.而很多其他文章比较时采用循环的方式当然会慢,但是不符合真实速度.
其次是求积
同样采用mylist数据作为基础,再次比较两者速度
# list
from time import time
start = time()
total = 1
for i in mylist:
total *= i
end = time()
print(f"total:{end-start}s")
## 50005000
## total:0.0003197193145751953s
# numpy np.sum
import numpy as np
myarray = np.array(mylist)
start = time()
total = np.prod(myarray)
end = time()
print(f"total:{end-start}s")
## total:0.01838994026184082s
## total:0.000213623046875s
在进行连乘时,由于原生 list 没有像 np.prod 这样直接面向数值数组的函数,通常就需要显式循环,这会明显拖慢速度。而 NumPy 由于有 np.prod,在这一类批量数值运算上通常更有优势。
总结
本文从实际运算的角度比较了 Python 内置 list 与 NumPy array 的一些差异。单看某些小规模求和场景,NumPy 未必一定更快,而且类型转换本身也有成本;但在批量数值运算、向量化操作、科学计算和机器学习场景里,NumPy 依然是更常见也更合适的选择。
总的来说,list 胜在通用、灵活、适合混合类型数据;numpy.array 胜在数值计算能力、生态兼容性和大规模数组处理效率。
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/321.html
- 版权声明:本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。