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)并相应地装饰该功能。或者只是将该函数的结果绑定到某个(全局)变量并使用该变量而不是再次调用该函数。无需在功能中使用全局。 –
你是否想在这里使用高阶函数?无论如何,我不明白你为什么不在模块级别的范围内制作字典。 –