如何读取Pokemon JSON文件并计算指定宝可梦的技能值?
问题:计算指定宝可梦的唯一技能ID数量
需求说明
给定宝可梦JSON文件路径和宝可梦名称,实现compute_pokemon_skills函数,统计该宝可梦所有技能子列表中唯一技能ID的总数。以Bulbasaur为例,预期输出为67。
输入示例
path = 'datasets/pokedex.json' name = 'Bulbasaur'
Bulbasaur技能数据示例
"skills": {"egg": [133, 204, 174, 203, 202, 320, 580, 275, 437, 345, 267, 80, 438, 130, 124], "level_up": [33, 45, 73, 22, 77, 79, 36, 75, 230, 74, 38, 388, 235, 402], "tm": [92, 474, 237, 241, 113, 182, 219, 218, 76, 216, 104, 188, 263, 156, 213, 496, 497, 412, 148, 14, 447, 207, 214, 164, 249, 267, 590, 15, 70], "transfer": [20, 520, 282, 173, 331, 290, 445, 363], "tutor": [520]}
已完成部分代码
import json path = 'datasets/pokedex.json' name = "Bulbasaur" def compute_pokemon_skills(path: str, name: str) -> int: with open(path) as f: pokedex = json.load(f) ... compute_pokemon_skills(path, name)
完整实现代码
import json path = 'datasets/pokedex.json' name = "Bulbasaur" def compute_pokemon_skills(path: str, name: str) -> int: with open(path) as f: pokedex = json.load(f) # 定位目标宝可梦的技能数据 target_pokemon = next(pokemon for pokemon in pokedex if pokemon['name'] == name) skill_groups = target_pokemon['skills'] # 收集所有技能ID并自动去重 unique_skill_ids = set() for skill_list in skill_groups.values(): unique_skill_ids.update(skill_list) # 返回唯一技能ID的数量 return len(unique_skill_ids) # 验证输出 print(compute_pokemon_skills(path, name)) # 输出:67
关键步骤说明
- 定位目标宝可梦:假设JSON根结构是宝可梦对象的列表,使用
next()快速找到名称匹配的宝可梦条目。 - 提取技能数据:从目标宝可梦对象中取出
skills字典,包含不同获取方式的技能列表。 - 去重统计:利用集合的唯一性特性,遍历所有技能子列表并将ID加入集合,最终集合的长度就是唯一技能ID的总数。
内容的提问来源于stack exchange,提问作者mongol
相关产品推荐
相关产品推荐

