[英]What is a faster version of this code instead of the double for-loop (python)?
[英]What is alternative for `:=` in lower python version for this for-loop?
我們可以在不使用:=
的情況下縮短此代碼,因為我的 python 版本低於3.8
嗎?
arr = [3,2,1,0]
ml = .7
arrSum = 0
res = []
for a in reversed(arr):
arrSum = a + ml*arrSum
res.append(arrSum)
res[::-1]
# [4.89, 2.7, 1.0, 0.0]
與:=
:
>>> arrSum = 0
>>> [arrSum := a + ml*arrSum for a in reversed(arr)][::-1]
[4.89, 2.7, 1.0, 0.0]
沒關系,如果解決方案是numpy
或...。
您可以使用例如itertools
:
from itertools import accumulate
ml = 0.7
arr = [3, 2, 1, 0]
list(accumulate(arr[::-1], lambda x,y: ml * x + y))[::-1]
它給:
[4.89, 2.7, 1.0, 0]
numpy
是另一種選擇:
import numpy as np
np.convolve(ml**np.arange(len(arr)), arr[::-1])[len(arr)-1::-1]
arrSum = 0
[arrSum := a + ml*arrSum for a in reversed(arr)][::-1]
可以改寫為
arrsum = 0
def fn(x):
nonlocal arrsum # or 'global arrsum' depending on the context
arrsum = x
return x
[fn(a + ml*arrSum) for a in reversed(arr)][::-1]
並不是說這樣做是個好主意……但這是在早期 Python 版本中模擬:=
的直接方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.