1
我需要在閱讀龐大文件後填充字典。我已經創建了一個讀取文件並填寫此字典的方法。每次迭代都會調用此方法,這會降低性能。無論如何,我可以通過它將靜態字典聲明爲該靜態字典,並且它在應用程序的整個生命週期中保持不變。Python中的字典的靜態行爲
我試圖模擬下面的代碼(使用nonlocal),但沒有幫助。該文件在每次迭代中都被讀取。
def read_data_from_file(path):
file_name = path + '.dat'
common_array_dict = dict()
def get_the_dict():
try:
common_array_list = list()
nonlocal common_array_dict
if common_array_dict :
return common_array_dict
with open(file_name, 'rb') as file:
new_list = pickle.load(file)
print("Reading file")
for do_operations here:
<stat1>
<stat2>
except IOError:
print("Output file doesn't exist! Continuing..")
return
return get_the_dict
任何建議將有助於:)
最簡單的方法是查找一些[memoization裝飾](https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)並相應地裝飾該功能。或者只是將該函數的結果綁定到某個(全局)變量並使用該變量而不是再次調用該函數。無需在功能中使用全局。 –
你是否想在這裏使用高階函數?無論如何,我不明白你爲什麼不在模塊級別的範圍內製作字典。 –