2017-01-30 172 views
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 

任何建议将有助于:)

+1

最简单的方法是查找一些[memoization装饰](https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize)并相应地装饰该功能。或者只是将该函数的结果绑定到某个(全局)变量并使用该变量而不是再次调用该函数。无需在功能中使用全局。 –

+2

你是否想在这里使用高阶函数?无论如何,我不明白你为什么不在模块级别的范围内制作字典。 –

回答

1

最简单的方法是看一些记忆化的装饰,例如从here,并相应地装饰该功能,然后在您的代码中正常使用它。每个文件只能读取一次,结果将被存储在缓存中供以后使用。

@memoize 
def read_data_from_file(path): 
    ... 

另外,只要绑定该函数的一些(可能是全局)变量的结果,并使用该变量,而不是再次调用该函数。无需在函数本身内使用全局。

data = read_data_from_file("the/path/to/the/file") 
.... 
do_stuff_with(data) # use result from function 
... 
do_more_stuff(data) # don't call read_data_from_file again