关于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设计】。

相关文章

centos6.5安装python3.7.1之后无法使用pip的解决方案

编译安装全是坑…… 第一遍装完无法使用pip,报错找不到ssl模块。各种报错: pip is configured with locations that require TLS/SS...

Tensorflow 自定义loss的情况下初始化部分变量方式

一般情况下,tensorflow里面变量初始化过程为: #variables ........... #..................... init = tf....

python 遍历pd.Series的index和value

遍历pd.Series的index和value的方法如下,python built-in list的enumerate方法不管用 for i, v in s.items(): p...

详解Python中的array数组模块相关使用

初始化 array实例化可以提供一个参数来描述允许那种数据类型,还可以有一个初始的数据序列存储在数组中。 import array import binascii s = 'Thi...

python自定义函数实现一个数的三次方计算方法

python自定义函数实现一个数的三次方计算方法

python自定义函数在运行时,最初只是存在内存中,只有调用时才会触发运行。 def cube_count(a): if is_number(a): return a**...