我有一個嵌套的 for 回圈,我正在對它進行一些操作,但是運行大約需要 20 分鐘。希望減少掛墻時間。這只是一個可重現的簡單示例,但是我如何重寫這個嵌套的 for 回圈以使其更高效?
我嘗試zip在 python 中使用該函式,但它不會i,j以與嵌套回圈相同的方式列印出順序,這是我的計算所必需的。
這個問題類似于this stackoverflow one,但我正在努力重現答案: Automatically nested for loops in python
array = np.random.rand(3,4,10)
x_vals = np.array([22,150,68,41]) #size of 4 (same as size as 2nd axis of array above)
new_arr = np.zeros((array.shape))
for i in range(3):
for j in range(4):
print(i,j)
new_arr[i,:,j] = array[i,:,j]*x_vals
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
我試過:
for i,j in zip(range(3),range(4)):
print(i,j) # output is i,j is not the same as it is for the nested loop above
0 0
1 1
2 2
我在想也許這個函式enumerate也能作業,但我也收到了一個錯誤:
for idx,i in enumerate(range(3),range(4)):
print(idx,i)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/tmp/ipykernel_2101160/1601005143.py in <module>
----> 1 for idx,i in enumerate(range(3),range(4)):
2 print(idx,i)
TypeError: 'range' object cannot be interpreted as an integer
關于如何矢量化或加速嵌套回圈的任何想法?
uj5u.com熱心網友回復:
您可以使用itertools.product如下,以避免嵌套for小號
import itertools
for i,j in itertools.product(range(3),range(4)):
print(i,j)
輸出
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
然而,它對所需的時間影響不大。你的提及
i,j(...) 的順序是我計算所必需的。
建議您需要先前計算的效果,即對無法打破的訂單有一定的規則。您需要考慮如何在不違反規則的情況下進行更改,以及它是否會提供所需的速度提升。
uj5u.com熱心網友回復:
您可以itertools.product在生成器運算式中使用, 等效于嵌套的 for 回圈。
https://docs.python.org/3/library/itertools.html#itertools.product
import itertools
for i, j in itertools.product(range(3), range(4)):
print(i, j)
uj5u.com熱心網友回復:
一種方法是使用np.mgrid生成索引并利用 numpy 索引(參見此處)來避免任何 for 回圈:
import numpy as np
array = np.random.rand(3, 4, 10)
x_vals = np.array([22, 150, 68, 41]) # size of 4 (same as size as 2nd axis of array above)
new_arr = np.zeros(array.shape)
rows, cols = map(np.ndarray.flatten, np.mgrid[0:3, 0:4])
new_arr[rows, :, cols] = array[rows, :, cols] * x_vals
uj5u.com熱心網友回復:
只要列印是可選的,以下內容將以矢量化方式完成:
array = np.random.rand(3,4,10)
x_vals = np.array([22,150,68,41])
new_arr = array*x_vals.reshape((1,4,1))
這也假設您實際上想要j一直運行到 10,而不是像示例中那樣在 4 處停止
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338366.html
上一篇:Python讀取字符
