我正在尝试使用range()
从自定义范围填充字典列表中的值。
我有这样的代码:
import requests
import json
import time
test = []
for x in range(5000,5020):
page_url = f'https://api.jikan.moe/v4/anime/{x}/full'
response = requests.get(page_url)
json_data = json.loads(response.text)
test.append(json_data)
time.sleep(1)
anime_data = []
for dic in test:
anime = {
'call_id': range(5000,5020),
'title': dic.get('data',{}).get('title','title not found'),
'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
'url': dic.get('data',{}).get('url', 'url not found')
}
anime_data.append(anime)
目标是对每个字典的'call_id'
键按顺序使用从5000到5020的数字,以便输出如下所示:
[{'call_id': 5000,
'title': 'title not found',
'mal_id': 'id not found',
'url': 'url not found'},
{'call_id': 5001,
'title': 'title not found',
'mal_id': 'id not found',
'url': 'url not found'},
{'call_id': 5002,
'title': 'Bari Bari Densetsu',
'mal_id': 5002,
'url': 'https://myanimelist.net/anime/5002/Bari_Bari_Densetsu'}]
代码没有按预期工作。我怎样才能得到想要的结果?
解决问题的另一种方法:从根本上说,我们希望并行迭代两个列表-原始API响应和我们想要在anime
条目中使用的数字(来自range
)。因此,朴素的响应是使用zip
,因此:
for call_id, dic in zip(range(5000, 5020), test):
anime = {
'call_id': call_id,
'title': dic.get('data',{}).get('title','title not found'),
'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
'url': dic.get('data',{}).get('url', 'url not found')
}
anime_data.append(anime)
但是,这忽略了一个更具体的内置工具:内置enumerate
函数。我们只需要适当地设置start
点;我们不需要担心有多少元素——它会一直递增,直到用完为止。
看起来像:
for call_id, dic in enumerate(test, 5000):
anime = {
'call_id': call_id,
'title': dic.get('data',{}).get('title','title not found'),
'mal_id': dic.get('data',{}).get('mal_id', 'id not found'),
'url': dic.get('data',{}).get('url', 'url not found')
}
anime_data.append(anime)
因为已经有一个循环来生成所有与in range(5000,5020)
相同的'call_id'
值—为了首先进行API调用—一个简单的方法是在第一个循环中直接创建最终数据,而不是存储json_data
结果并尝试在稍后的循环中处理它们。它看起来像:
anime_data = []
for x in range(5000,5020):
page_url = f'https://api.jikan.moe/v4/anime/{x}/full'
response = requests.get(page_url)
json_data = json.loads(response.text)
anime = {
'call_id': x,
'title': json_data.get('data',{}).get('title','title not found'),
'mal_id': json_data.get('data',{}).get('mal_id', 'id not found'),
'url': json_data.get('data',{}).get('url', 'url not found')
}
anime_data.append(anime)
time.sleep(1)
我们可以通过使用函数拆分每次通过循环执行的任务,并通过预计算.get('data',{})
结果来更好地组织逻辑:
def query_api(anime_id):
page_url = f'https://api.jikan.moe/v4/anime/{anime_id}/full'
response = requests.get(page_url)
return json.loads(response.text).get('data',{})
def make_anime_data(anime_id, raw_data):
return {
'call_id': anime_id,
'title': raw_data.get('title','title not found'),
'mal_id': raw_data.get('mal_id', 'id not found'),
'url': raw_data.get('url', 'url not found')
}
anime_data = []
for x in range(5000,5020):
raw_data = query_api(x)
anime_data.append(make_anime_data(x, raw_data))
time.sleep(1)