Python:嵌套的iteritems循环只运行一次

时间:2016-04-11 07:38:15

标签: python dictionary

我试图遍历字典,并在其中附加字典。但是当我使用iteritems()循环时,它只迭代一次并退出到外循环。我在python中很新,但我认为这段代码应该正常工作。

为什么会这样?

from __future__ import division
import numpy
import pprint

training = {"outlook":{"sunny":{"yes":2,"no":3},"overcast":{"yes":4,"no":0},"rainy":{"yes":3,"no":2}},\
            "temperature":{"yes":[83,70,68,64,69,75,75,72,81],"no":[85,80,65,72,71]},\
            "humidity":{"yes":[86,96,80,65,70,80,70,90,75],"no":[85,90,70,95,91]},\
            "windy":{"false":{"yes":6,"no":2},"true":{"yes":3,"no":3}},\
            "play":{"yes":9,"no":5}}
processed = {}
total_yes = training["play"]["yes"]
total_no = training["play"]["no"]
total_all = training["play"]["no"]+training["play"]["yes"]

def main():
    for k,v in training.iteritems():
        if(k != "play"):
            for k2,v2 in v.iteritems():
                if((k2 == "yes") & isinstance(v2,list)):
                    processed[k] = {"yes":{"mean":numpy.mean(v2),"std":numpy.std(v2,ddof=1)}}
                elif((k2 == "no") & isinstance(v2,list)):
                    processed[k].update({"no":{"mean":numpy.mean(v2),"std":numpy.std(v2,ddof=1)}})
                else:
                    processed[k] = {}

                    # the problems start here
                    for i,j in v2.iteritems():
                        if(i == "yes"):
                            p_yes = j/total_yes
                            processed[k].update({k2:{"yes":p_yes,"no":(1-p_yes)}})
                        #when I print processed[k], it contains current value only (not including previous value)
                #suddenly exit after iterating once

        else:
            processed[k] = {"yes":total_yes/total_all,"no":total_no/total_all}

    pp = pprint.PrettyPrinter(indent=3)
    pp.pprint(processed)

if __name__ == '__main__':
    main()

输出结果为:

...
'outlook': {  'sunny': {  'no': 0.7777777777777778,
                          'yes': 0.2222222222222222}},
...

但预期产出是:

...
'outlook': {  'sunny': {  'no': 0.7777777777777778,
                          'yes': 0.2222222222222222}},
              'overcast': { 'no':xxxxx,
                            'yes':xxx
                          }
              ...
...

1 个答案:

答案 0 :(得分:0)

问题在于:

else:
    processed[k] = {}

当你的for循环移动到下一个元素时,k的前一个值被覆盖。

在此处定义此问题并解决您的问题:

for k,v in training.iteritems():
    if(k != "play"):
        processed[k] = {}