计算一个值在任意嵌套列表中出现的次数
Count the number of times a value exists in arbitrary nested lists
我有一个这样的 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" 在 "scripts" 下出现的次数。但我不确定如何遍历列表的列表....在 "scripts".
下
这是我的代码:
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 列表中。
从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:
出现在脚本中的次数。
我有一个这样的 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" 在 "scripts" 下出现的次数。但我不确定如何遍历列表的列表....在 "scripts".
下这是我的代码:
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 列表中。
从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:
出现在脚本中的次数。