计算值在任意嵌套列表中存在的次数

2024-10-02 12:34:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个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": ""
                    }],

        }
}

我想计算“脚本”下出现“按键”的次数。但是我不知道如何遍历列表。。。。在“脚本”下。你知道吗

这是我的密码:

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)

我想在按键列表中存储按键次数。你知道吗


Tags: in脚本json列表fordatagetas
1条回答
网友
1楼 · 发布于 2024-10-02 12:34:58

借用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:在脚本中出现的次数。你知道吗

相关问题 更多 >

    热门问题