开发者

working with dictionary in python

开发者 https://www.devze.com 2023-01-16 02:32 出处:网络
I have this dictionary goodDay= {\'Class\':[1,1,0,0,0,1,0,1,0,1], \'grade\':[1,0,0,1,0,1,0,1,0,1]} I want to traverse the values of first key and also of second and put this condition to check:

I have this dictionary

goodDay= {'Class':[1,1,0,0,0,1,0,1,0,1], 'grade':[1,0,0,1,0,1,0,1,0,1]}

I want to traverse the values of first key and also of second and put this condition to check:

If value of K2 is 1 how many times is K1 is 1 and K1 is 0 开发者_如何学C and if K2 is 0 how many times is K1 is 0 and K1 is 1.


c = [[0,0],[0,0]]
for first, second in zip(goodDay['class'], goodDay['grade']):
  c[second][first] += 1

You compare the two lists in the dictionary pairwise, since each of the lists has only two values (0 and 1), this means that together(cartesian product) we can have 4 different options (00, 01, 10, 11). So we use 2*2 list to store these. And then iterate through both lists and remember the count into the list. So at the end of execution of above lines, we can read the results from list c as follows:

c[0][0] is the number of zeros in goodDay['class'] where at the same location in goodDay['grade'] is zero
c[0][1] is the number of zeros in goodDay['class'] where at the same location in goodDay['grade'] is one
c[1][0] is the number of ones in goodDay['class'] where at the same location in goodDay['grade'] is zero
c[1][1] is the number of ones in goodDay['class'] where at the same location in goodDay['grade'] is one


Code:

good_day= {'class':[1,1,0,0,0,1,0,1,0,1], 'grade':[1,0,0,1,0,1,0,1,0,1]}
grade_class = [[0,0],
               [0,0]]

for grade, class_ in zip(good_day['grade'], good_day['class']):
    grade_class[grade][class_] += 1

for class_ in (0,1):
    for grade in (0,1):
        print 'You had', grade_class[grade][class_], 'grade', \
              grade, 'when your class was', class_

Output:

You had 4 grade 0 when your class was 0
You had 1 grade 1 when your class was 0
You had 1 grade 0 when your class was 1
You had 4 grade 1 when your class was 1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号