简体   繁体   English

如何使用字典修复无限While循环

[英]How to fix an infinite while loop with dictionaries

I am trying to iterate through the dictionary shown in the picture where I have to retrieve the value of key 'time' whenever the key code = '36' between tag = 'new battery'. 我试图遍历图片中显示的字典,只要标签=“新电池”之间的键代码=“ 36”,我就必须检索键“时间”的值。

In other words, from the very first time 'tag' == 'new battery' I've to find the time when code == '36' until the next time 'tag' == 'new battery'. 换句话说,从第一次“标签” ==“新电池”开始,我必须找到代码==“ 36”时的时间,直到下一次“标签” ==“新电池”。 It should do this until we finish parsing the dictionary. 它应该这样做直到我们完成对字典的解析。 Any help will be appreciated. 任何帮助将不胜感激。

词典图片

I did a while loop and tried it but i am stuck with an infinite loop. 我做了一个while循环并尝试了一下,但是我陷入了无限循环。 I am brand new to Python. 我是Python的新手。 Sorry for being unreadable, but I did the best that I could. 抱歉,无法理解,但我已尽力而为。

for key in d:
       while(d[key]['type'] != '44'): 
          if d[key]['code']=='36':
            time_6=d[key]['time']
            print(time_6)

            countlist.append(time_6)

As from my understanding this code will help to resolve your query. 据我了解,此代码将有助于解决您的查询。 We are changing a little bit in your code.you have to reiterate between key when first time and last time tag new battery called. 我们在您的代码中做了一些更改。您必须在第一次和最后一次标记新电池时在按键之间重复。

for key in d:
       if(d[key]['type'] == '44'):
           key_bw_nw_battery.append(key)
for f in range(min(key_bw_nw_battery),max(key_bw_nw_battery),1):
       if d[f]['code']=='36':
       time_6=d[f]['time']
       print(time_6)
       countlist.append(time_6)

As far as I can tell, there is no need for this code to use double loops (quadratic behaviour), a while , or even the dictionary keys. 据我所知,此代码无需使用双循环(二次行为), while甚至是字典键。

for item in d.values():
    if item['type'] != '44' and item['code'] == '36':
        time_6 = item['time']
        print(time_6)

        countlist.append(time_6)

The key thing to remember about while is that something must be changing in the condition it's testing. 要记住的关键一点while是必须的东西,在它的测试条件正在发生变化。 It doesn't advance on its own like for does, so you were testing the same item repeatedly. 它不会像for那样单独前进,因此您要反复测试同一项目。 Since the while was inside the for , the for couldn't advance until the while ended (which it never did). 由于whilefor ,因此for不能前进,直到while结束(它从来没有这样做)。

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

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