在Python中的函数中使用大数据结构时的效率

前端之家收集整理的这篇文章主要介绍了在Python中的函数中使用大数据结构时的效率前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我需要使用大数据结构,更具体地说,使用大字典来完成查找工作.

在最初我的代码是这样的:

  1. #build the dictionary
  2. blablabla
  3. #look up some information in the ditionary
  4. blablabla

由于我需要多次查看,我开始意识到将它实现为函数是个好主意,比如查找(info).

然后问题来了,我应该如何处理大字典?

我应该使用lookup(info,dictionary)将其作为参数传递,还是应该只在main()中初始化字典并将其用作全局变量

第一个似乎更优雅,因为我认为维护全局变量很麻烦.
但另一方面,我不确定将大字典传递给函数的效率.它将被多次调用,如果传递的参数效率低下,它肯定会成为一场噩梦.

谢谢.

EDIT1:

我刚刚对上述两种方式进行了实验:

这是代码的片段. lookup1实现传递查找的参数,而lookup2使用全局数据结构“big_dict”.

  1. class CityDict():
  2. def __init__():
  3. self.code_dict = get_code_dict()
  4. def get_city(city):
  5. try:
  6. return self.code_dict[city]
  7. except Exception:
  8. return None
  9. def get_code_dict():
  10. # initiate code dictionary from file
  11. return code_dict
  12. def lookup1(city,city_code_dict):
  13. try:
  14. return city_code_dict[city]
  15. except Exception:
  16. return None
  17. def lookup2(city):
  18. try:
  19. return big_dict[city]
  20. except Exception:
  21. return None
  22. t = time.time()
  23. d = get_code_dict()
  24. for i in range(0,1000000):
  25. lookup1(random.randint(0,10000),d)
  26. print "lookup1 is %f" % (time.time() - t)
  27. t = time.time()
  28. big_dict = get_code_dict()
  29. for i in range(0,1000000):
  30. lookup2(random.randint(0,1000))
  31. print "lookup2 is %f" % (time.time() - t)
  32. t = time.time()
  33. cd = CityDict()
  34. for i in range(0,1000000):
  35. cd.get_city(str(i))
  36. print "class is %f" % (time.time() - t)

这是输出

lookup1 is 8.410885
lookup2 is 8.157661
class is 4.525721

所以似乎两种方式几乎相同,是的,全局变量方法更有效.

EDIT2:

添加了Amber建议的类版本,然后再次测试效率.然后我们可以从结果中看出Amber是对的,我们应该使用类版本.

最佳答案
都不是.使用专门用于将函数(方法)与数据(成员)分组的类:

  1. class BigDictLookup(object):
  2. def __init__(self):
  3. self.bigdict = build_big_dict() # or some other means of generating it
  4. def lookup(self):
  5. # do something with self.bigdict
  6. def main():
  7. my_bigdict = BigDictLookup()
  8. # ...
  9. my_bigdict.lookup()
  10. # ...
  11. my_bigdict.lookup()

猜你在找的Python相关文章