繁体   English   中英

提高iteritems的性能或更好的遍历python字典的方法

[英]improve iteritems performance or a better way to loop through python dictionary

大约需要 190s可以在配备Intel i5、8GB,Windows 7的笔记本电脑上完成以下循环。

count = 0
for l in xrange(NUM_ROOM): 
    for k in xrange(NUM_SLOT):
        for m in xrange(NUM_ACTIVITY):
            count = count+1

            for dk, [om, ol, ok] in xDict.iteritems(): 
                if dk == (m,l,k):
                    # do something

我进行了跟踪,发现总循环为13960 x 19040〜2bils。

len(self.xDict): 13960
count: 19040

xDict看起来像这样(一个示例):

xDict = {(19, 4, 118): [19, 4, 4], (4, 12, 25): [4, 12, 7], (15, 19, 121): [15, 19, 21], (23, 5, 219): [23, 5, 9], (13, 5, 19): [13, 5, 1]}                 

我正在尝试获取字典中某个键的值。 无论如何,有没有改善性能的方法?


对不起,我想我知道会发生什么。

count = 0
for l in xrange(NUM_ROOM): 
    for k in xrange(NUM_SLOT):
        for m in xrange(NUM_ACTIVITY):
            count = count+1

            val = xDict.get((m,l,k))
            if val != None:  
                [om, ol, ok] = val  
                # do something

现在需要1秒。

不要仅仅为了找到一把钥匙就遍历所有物品。 请使用会员资格测试:

if (m, l, k) in xDict:
    om, ol, ok = xDict[m, l, k]

这样就无需为19040次迭代中的每个循环遍历13960个项目。

如果您还使用mlk进行其他操作,那么您没有告诉我们您要在此处实现的目标的太多信息,而是考虑仅遍历键; 这样,您就可以将其减少到超过13960个项目的循环,而不是19040次迭代。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM