所以我要遍历一些JSON数据,这很慢,因为我使用嵌套的for循环。
我的代码如下:
import requests
import json
pokemon_url = 'https://pokeapi.co/api/v2/pokemon/bulbasaur/'
pokemon_move_url = 'https://pokeapi.co/api/v2/move/pound/'
pokemon_info = requests.get(pokemon_url)
pokemon_data = pokemon_info.text
pokemon_parsed = json.loads(pokemon_data)
name = pokemon_parsed['forms'][0]['name']
for move in pokemon_parsed['moves']:
for method in move['version_group_details']:
if method['version_group']['name'] == 'sun-moon' and method['move_learn_method']['name'] == 'level-up':
pokemon_move_url = 'https://pokeapi.co/api/v2/move/'+move['move']['name']
pokemon_move = requests.get(pokemon_move_url)
pokemon_move_text = pokemon_move.text
pokemon_parsed_moves = json.loads(pokemon_move_text)
print(method['move_learn_method']['name'],move['move']['name'],method['level_learned_at'],pokemon_parsed_moves['type']['name'],pokemon_parsed_moves['power'],pokemon_parsed_moves['accuracy'])
我想知道如何才能更有效,更好地做到这一点。我知道有更好的方法,但是我刚开始使用Python,所以我还在学习。
答案 0 :(得分:0)
正如Sergio所提到的,http请求可能比for循环慢,但是当您有大量迭代时,for循环会降低速度。您可以尝试使用列表理解来构建网址列表,然后执行请求: 对于内循环的第一行,将是:
pokemon_move_url = ['https://pokeapi.co/api/v2/move/'+move['move']['name'] for move in pokemon_parsed['moves'] for method in move['version_group_details'] if method['version_group']['name'] == 'sun-moon' and method['move_learn_method']['name'] == 'level-up']
pokemon_move = [requests.get(url) for url in pokemon_move_url]
pokemon_move_text = [move.text for move in pokemon_move]
pokemon_parsed_moves = [json.loads(text) for text in pokemon_move_text]
这应该比使用for循环快得多(当然,这取决于for循环或请求是瓶颈)