1
我必須多次計算一個函數。 要計算此函數,必須計算數組的元素。 陣列非常大。Python多次避免大數組分配
如何避免在每個函數調用中分配數組。
我曾嘗試代碼都東西這樣的:
class FunctionCalculator(object):
def __init__(self, data):
"""
Get the data and do some small handling of it
Let's say that we do
self.data = data
"""
def function(self, point):
return numpy.sum(numpy.array([somecomputations(item) for item in self.data]))
好吧,也許我的擔心是沒有根據的,所以我必須首先這個問題。
問:這是真的,該陣列[somecomputations(item) for item in data]
被分配和釋放每次調用function
?
以爲那就是我試圖
class FunctionCalculator(object):
def __init__(self, data):
"""
Get the data and do some small handling of it
Let's say that we do
self.data = data
"""
self.number_of_data = range(0, len(data))
self.my_array = numpy.zeros(len(data))
def function(self, point):
for i in self.number_of_data:
self.my_array[i] = somecomputations(self.data[i])
return numpy.sum(self.my_array)
這比以前的版本更慢的情況。我假設第一版本中的列表理解完全可以用C語言運行,而在第二版本中,腳本的較小部分可以轉換爲優化的C代碼。
我對Python是如何工作的想法很少。
問題:有沒有一種很好的方法可以跳過每個函數調用中的數組分配,並同時利用數組上的優化循環?
我使用Python3.5
爲了將numpy數組傳遞給我的函數,函數必須包含numpy知道的操作嗎?我不太明白。 – myfirsttime1
哦!我剛剛瞭解到有一個'numpy.vectorize',你可以傳遞一個函數。這可能有幫助。 – myfirsttime1
這不是必須的。作爲簡單算術表達式的函數按原樣工作。 – kabanus