关于Python中的向量相加和numpy中的向量相加效率对比
作者:boyan_RF 时间:2022-09-30 04:22:44
直接使用Python来实现向量的相加
# -*-coding:utf-8-*-
#向量相加
def pythonsum(n):
a = range(n)
b = range(n)
c = []
for i in range(len(a)):
a[i] = i**2
b[i] = i**3
c.append(a[i]+b[i])
return a,b,c
print pythonsum(4),type(pythonsum(4))
for arg in pythonsum(4):
print arg
从这里这个输出结果可以看得出来,return多个值时,是以列表的形式返回的
([0, 1, 4, 9], [0, 1, 8, 27], [0, 2, 12, 36]) <type 'tuple'>
[0, 1, 4, 9]
[0, 1, 8, 27]
[0, 2, 12, 36]
使用numpy包实现两个向量的相加
def numpysum(n):
a = np.arange(n) ** 2
b = np.arange(n) ** 3
c = a + b
return a,b,c
(array([0, 1, 4, 9]), array([ 0, 1, 8, 27]), array([ 0, 2, 12, 36])) <type 'function'>
[0 1 4 9]
[ 0 1 8 27]
[ 0 2 12 36]
比较用Python实现两个向量相加和用numpy实现两个向量相加的情况
size = 1000
start = datetime.now()
c = pythonsum(size)
delta = datetime.now() - start
# print 'The last 2 elements of the sum',c[-2:]
print 'pythonSum elapsed time in microseconds',delta.microseconds
size = 1000
start1 = datetime.now()
c1 = numpysum(size)
delta1 = datetime.now() - start1
# print 'The last 2 elements of the sum',c1[-2:]
print 'numpySum elapsed time in microseconds',delta1.microseconds
从下面程序运行结果我们可以看到在处理向量是numpy要比Python计算高出不知道多少倍
pythonSum elapsed time in microseconds 1000
numpySum elapsed time in microseconds 0
来源:https://blog.csdn.net/zhongjunlang/article/details/78137802
标签:Python,向量,相加,numpy
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
微软建议的ASP性能优化28条守则(5)
2008-02-27 13:54:00
关联的 script 标签
2009-11-02 10:40:00
django ajax发送post请求的两种方法
2022-06-21 07:06:51
正则表达式的基本概念
2007-10-17 21:07:00
关于Python dict存中文字符dumps()的问题
2022-08-22 17:53:17
![](https://img.aspxhome.com/file/2023/7/79507_0s.png)
浅谈Python之Django(三)
2021-07-07 00:38:25
![](https://img.aspxhome.com/file/2023/3/77743_0s.png)
浅谈DataFrame和SparkSql取值误区
2021-03-21 22:04:18
![](https://img.aspxhome.com/file/2023/8/85208_0s.jpg)
Python TCPServer 多线程多客户端通信的实现
2021-07-05 22:33:00
![](https://img.aspxhome.com/file/2023/2/75092_0s.png)
H1标签的定义
2008-07-29 12:43:00
![](/images/sg_trans.gif)
Python控制浏览器自动下载歌词评论并生成词云图
2022-04-17 11:24:56
![](https://img.aspxhome.com/file/2023/9/83679_0s.png)
JavaScript 设计模式 富有表现力的Javascript(一)
2023-08-25 07:42:15
Array.prototype.slice
2010-05-07 12:43:00
WEB2.0网页制作标准教程(5)head区的其他设置
2007-11-13 13:28:00
巧用Dreamweaver MX共享Execl XP文件
2009-07-14 21:56:00
Python爬取豆瓣数据实现过程解析
2022-01-27 09:12:20
![](https://img.aspxhome.com/file/2023/2/86252_0s.png)
Keras构建神经网络踩坑(解决model.predict预测值全为0.0的问题)
2023-03-28 04:05:22
Python reques接口测试框架实现代码
2023-10-07 12:47:08
![](https://img.aspxhome.com/file/2023/9/63219_0s.png)
网页超级链接加上快捷键方法
2010-03-16 12:28:00
回顾Javascript React基础
2023-07-13 00:57:00
html风格tooltip效果的实现
2010-04-08 13:00:00