关于Python中的向量相加和numpy中的向量相加效率对比

yipeiwu_com6年前Python基础

直接使用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

以上这篇关于Python中的向量相加和numpy中的向量相加效率对比就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

django与小程序实现登录验证功能的示例代码

之前用小程序做项目,因为后台使用的java开发,一切顺利,但切换成django做RESTful API接口时,在登陆注册时一直出现问题,网上搜索,借助一个网友的回答,找到了一种可行的解决...

python集合是否可变总结

集合是一个无序的可变的序列。集合中的元素必须是可hash的,即不可变的数据类型。 空集合 a=set() 注意a={}创建的是一个空字典。 set —— 可变集合。集合中的元素可以动态...

在Python的列表中利用remove()方法删除元素的教程

 remove()方法从列表中删除第一个obj。 语法 以下是remove()方法的语法: list.remove(obj) 参数   &n...

Python 出现错误TypeError: ‘NoneType’ object is not iterable解决办法

Python 出现错误TypeError: ‘NoneType' object is not iterable解决办法 TypeError: 'NoneType' object is n...

Python中decorator使用实例

在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。 关于decorator的详细介绍在 Python...