你可以用切片:
In [14]: arr = np.arange(0, 10)
In [15]: arr
Out[15]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [16]: arr[::2]
Out[16]: array([0, 2, 4, 6, 8])
因此,你的函數只會是這樣的:
def hopSamples1(x, N):
return x[::N]
如果您有任何疑問在事先聲明空數組,並使用循環加油吧T,你可以改變你的函數一點做到以下幾點之一。
您可以初始化一個空數組,並在循環的每次迭代中通過另一個單元擴展它。請注意,每次都會創建並返回一個新數組。
def hopSamples2(x, N):
i = 0
n = len(x)
output = np.empty(shape = 0, dtype = x.dtype)
while i < n:
output = np.append(output, x[i])
i += N
return output
一種替代實現將預先創建整個陣列,但在設置這些值到它的細胞中一個接一個。
def hopSamples3(x, N):
i = 0
n = len(x)
m = n/N
output = np.ndarray(shape = m, dtype = x.dtype)
while i < m:
output[i] = x[i * N]
i += 1
return output
一個簡單的基準測試表明,使用切片是同時通過一個擴展陣列一個最快的方法是最慢的:
In [146]: %time hopSamples1(arr, 2)
CPU times: user 21 µs, sys: 3 µs, total: 24 µs
Wall time: 28.8 µs
Out[146]: array([0, 2, 4, 6, 8])
In [147]: %time hopSamples2(arr, 2)
CPU times: user 241 µs, sys: 29 µs, total: 270 µs
Wall time: 230 µs
Out[147]: array([0, 2, 4, 6, 8])
In [148]: %time hopSamples3(arr, 2)
CPU times: user 35 µs, sys: 5 µs, total: 40 µs
Wall time: 45.8 µs
Out[148]: array([0, 2, 4, 6, 8])
發佈你得到確切的錯誤將在未來有用,雖然你得到的答案是非常好的。 – porglezomp 2014-10-07 00:49:07
此外,你的問題標題並不真正適合你的問題的描述。爲「聲明(實際上,創建)一個空數組和填充」的方式是'np.zeros'加上正常索引設定。但是你想要做的並不是首先要做的。 – abarnert 2014-10-07 00:50:47
是的,對不起,我現在看到它。我對我在Python方面的知識缺乏表示歉意,上週我開始使用它。謝謝您的意見! – Hec46 2014-10-07 19:02:47