简体   繁体   English

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

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

It takes approx. 大约需要 190s to complete the loop below on a laptop with Intel i5, 8GB, Windows 7. 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

I did a trace and found out that the total loop is 13960 x 19040 ~ 2bils. 我进行了跟踪,发现总循环为13960 x 19040〜2bils。

len(self.xDict): 13960
count: 19040

xDict looks something like this (an example): 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]}                 

I am trying to get the value of a key in the dictionary. 我正在尝试获取字典中某个键的值。 Is there anyway to improve the performance? 无论如何,有没有改善性能的方法?


Sorry, I think I know what happen. 对不起,我想我知道会发生什么。

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

Now it takes 1s. 现在需要1秒。

Don't loop over all items just to find one key . 不要仅仅为了找到一把钥匙就遍历所有物品。 Use a membership test instead: 请使用会员资格测试:

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

This removes the need to loop over 13960 items for each of your 19040 iterations. 这样就无需为19040次迭代中的每个循环遍历13960个项目。

You haven't told us much about what you are trying to achieve here, if you are using m , l and k for something else too, but consider just looping over the keys instead; 如果您还使用mlk进行其他操作,那么您没有告诉我们您要在此处实现的目标的太多信息,而是考虑仅遍历键; that way you'd reduce this to a loop over 13960 items instead of 19040 iterations. 这样,您就可以将其减少到超过13960个项目的循环,而不是19040次迭代。

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

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