龙空技术网

python原生list数组与numpy的array

独一无二的Python君 217

前言:

现时咱们对“pythonprod函数”大约比较关怀,小伙伴们都想要了解一些“pythonprod函数”的相关内容。那么小编也在网摘上搜集了一些有关“pythonprod函数””的相关内容,希望咱们能喜欢,姐妹们一起来学习一下吧!

在python中存储集合数据可以选择多种原生数据类型,包括list,array,tuple,dictionary四种类型.其中list可变性强,可存储任意内容并且可变,应用范围广泛.而在进行科学运算,存储纯数字时,numpy被广泛应用,可以说基本完全替代了list.那么它们之间有何不同,差距到底有多大,实际过程中应该如何应用呢?

当然,使用实际案例最能说明问题.

运算速度比较

简单的加减乘除,以10000以内的数字做个比较.

首先是求和

mylist = []for i in range(1,10001):    mylist.append(i)#  listfrom time import timestart = time()total=sum(mylist)print(total)end = time()print(f"total:{end-start}s")## 50005000## total:0.0003197193145751953s# numpy  np.sumimport numpy as npmyarray = np.array(mylist)start = time()total = np.sum(myarray)print(total)end = time()print(f"total:{end-start}s")## 50005000## total:0.00041031837463378906s# numpy sumstart = 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数据作为基础,再次比较两者的速度

#  listfrom time import timestart = time()total = 1for i in total:    total *= iend = time()print(f"total:{end-start}s")## 50005000## total:0.0003197193145751953s# numpy  np.sumimport numpy as npmyarray = np.array(mylist)start = time()total = np.prod(myarray)end = time()print(f"total:{end-start}s")## total:0.01838994026184082s## total:0.000213623046875s

在进行连乘时,由于没有内置的乘法,只能采用循环的方式进行,不可避免的造成速度的降低,而numpy由于有prod函数,极大的提升了连乘的计算速度.

总结

本文从实际运算的角度比较了python内置的list与numpy的array的计算速度,发现在计算加和是numpy并不占优势,而且类型转换上会多消耗时间,而在计算连乘时numpy速度提升非常大,因此在计算连乘时numpy下频率高. 总的来说,list应用范围广,求和速度快.而在科学运算,机器学习等领域则使用numpy.因numpy的array在计算连乘等方面速度极快,并且由于pandas的dataframe,series等广泛应用在科学计算上占据绝对优势,也使得其依赖numpy在科学运算中占据绝对优势.

标签: #pythonprod函数