溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python和numpy中的向量相加哪個(gè)效率比較高

發(fā)布時(shí)間:2021-09-06 09:58:32 來源:億速云 閱讀:315 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Python和numpy中的向量相加哪個(gè)效率比較高”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Python和numpy中的向量相加哪個(gè)效率比較高”吧!

直接使用Python來實(shí)現(xiàn)向量的相加

# -*-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

從這里這個(gè)輸出結(jié)果可以看得出來,return多個(gè)值時(shí),是以列表的形式返回的

([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包實(shí)現(xiàn)兩個(gè)向量的相加

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實(shí)現(xiàn)兩個(gè)向量相加和用numpy實(shí)現(xiàn)兩個(gè)向量相加的情況

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

從下面程序運(yùn)行結(jié)果我們可以看到在處理向量是numpy要比Python計(jì)算高出不知道多少倍

pythonSum elapsed time in microseconds 1000
numpySum elapsed time in microseconds 0

感謝各位的閱讀,以上就是“Python和numpy中的向量相加哪個(gè)效率比較高”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)Python和numpy中的向量相加哪個(gè)效率比較高這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI