您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:20:41 python 字数 3863 阅读 437 来源 www.jb51.cc/python

我需要使用大数据结构,更具体地说,使用大字典来完成查找工作.在最初我的代码是这样的:#build the dictionary blablabla #look up some information in the ditionary blablabla 由于我需要多次查看,我开始意识到将它实现为函数是个好主意,比如查找(info).然后问题来了,我应该如何处

概述

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

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

#build the dictionary
blablabla
#look up some information in the ditionary
blablabla

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

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

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

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

谢谢.

EDIT1:

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

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

class CityDict():
    def __init__():
        self.code_dict = get_code_dict()
    def get_city(city):
        try:
            return self.code_dict[city]
        except Exception:
            return None         

def get_code_dict():
    # initiate code dictionary from file
    return code_dict

def lookup1(city,city_code_dict):
    try:
        return city_code_dict[city]
    except Exception:
        return None

def lookup2(city):
    try:
        return big_dict[city]
    except Exception:
        return None


t = time.time()
d = get_code_dict()
for i in range(0,1000000):
    lookup1(random.randint(0,10000),d)

print "lookup1 is %f" % (time.time() - t)


t = time.time()
big_dict = get_code_dict()
for i in range(0,1000000):
    lookup2(random.randint(0,1000))
print "lookup2 is %f" % (time.time() - t)


t = time.time()
cd = CityDict() 
for i in range(0,1000000):
    cd.get_city(str(i))
print "class is %f" % (time.time() - t)

这是输出

lookup1 is 8.410885
lookup2 is 8.157661
class is 4.525721

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

EDIT2:

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

class BigDictLookup(object):
    def __init__(self):
        self.bigdict = build_big_dict() # or some other means of generating it
    def lookup(self):
        # do something with self.bigdict

def main():
    my_bigdict = BigDictLookup()
    # ...
    my_bigdict.lookup()
    # ...
    my_bigdict.lookup()

总结

以上是编程之家为你收集整理的在Python中的函数中使用大数据结构时的效率全部内容,希望文章能够帮你解决在Python中的函数中使用大数据结构时的效率所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶