2015-11-17 96 views
0

存在一個值的次數我有一個JSON數據是這樣的:計數任意嵌套列表

{ 
    "children": [{ 
       "objName": "Sprite1", 
       "scripts": [[89, 68, [["whenGreenFlag"], ["doForever", [["doIf", ["keyPressed:", "space"], [["wait:elapsed:from:", 0.5], ["playSound:", "meow"]]], 
            ["doIf", ["mousePressed"], [["playDrum", 1, 0.25]]]]]]]], 
       "sounds": [{ 
         "soundName": "meow", 
         "soundID": 0, 
         "md5": "83c36d806dc92327b9e7049a565c6bff.wav", 
         "sampleCount": 18688, 
         "rate": 22050, 
         "format": "" 
        }], 

     } 
} 

我想要的「腳本」下算「的keyPressed」出現的次數。但我不知道如何在「腳本」下遍歷列表清單....

這是我的代碼:

import simplejson as json 

with open("D:\\1.SnD\Work\PyCharmProjects\project.json", 'rb') as f: 
    json_data = json.loads(str(f.read(), 'utf-8')) 
    key_presses = [] 
    for child in json_data.get('children'): 
     for script in child.get('scripts'): 
      for mouse in script.get("keyPressed"): // Does not work 
       print(mouse) 

我想存儲的keyPressed在key_presses列表計數。

回答

1

What is the fastest way to flatten arbitrarily nested lists in Python?借鑑優秀flatten方法,並將其與Counter從收藏相結合,您可以:

import collections, json 

def flatten(container): 
    for i in container: 
     if isinstance(i, list) or isinstance(i, tuple): 
      for j in flatten(i): 
       yield j 
     else: 
      yield i 

with open("D:\\1.SnD\Work\PyCharmProjects\project.json", 'rb') as f: 
    json_data = json.loads(str(f.read(), 'utf-8')) 

print(collections.Counter(
     flatten(json_data['children'][0]['scripts']))['keyPressed:']) 

如果你運行上面,輸出會的次數keyPressed:出現在腳本中。

+0

非常感謝,這工作完美! – Retr0spect