Python中如何保存for循环内多次API调用返回的多列表结果?
问题原因
你当前的写法在每次循环迭代时都会重新给response_3赋值,上一轮迭代拿到的API返回结果会被直接覆盖,循环执行完成后自然只能访问到最后一次迭代的输出。
方案1:将所有迭代返回结果合并为一个平铺总列表
这是批量数据采集场景最常用的处理方式,适合后续统一做数据清洗、入库的需求。
在循环外预先初始化一个空的总结果列表,由于api_call每次返回的是字典构成的列表,用extend()方法即可把单次返回的所有字典元素平铺追加到总列表中,不会产生嵌套结构。
all_api_results = [] for auto_sort in response_1: countryname = auto_sort['Country'] iso = auto_sort['ThreeLetterSymbol'] current_response = api_call(countryname, iso) # 注意不要用append,否则总列表会变成嵌套结构,每个元素是单次返回的小列表 all_api_results.extend(current_response)
循环执行完成后,all_api_results就是包含所有接口返回字典的总列表。
方案2:单独保存每一次迭代的输出
如果需要保留每次请求的独立结果,方便后续按请求维度溯源、排查问题,可以选择以下两种存储方式:
- 按遍历顺序存储:结果列表的索引和
response_1的遍历顺序一一对应
each_iter_results = [] for auto_sort in response_1: countryname = auto_sort['Country'] iso = auto_sort['ThreeLetterSymbol'] current_response = api_call(countryname, iso) each_iter_results.append(current_response)
- 按国家标识映射存储:以ISO三字母编码/国家名为key存储结果,查询指定国家的数据时不需要遍历匹配,效率更高
results_mapped_by_iso = {} for auto_sort in response_1: countryname = auto_sort['Country'] iso = auto_sort['ThreeLetterSymbol'] current_response = api_call(countryname, iso) results_mapped_by_iso[iso] = { "country_name": countryname, "response_data": current_response }
可选优化
如果API请求存在网络波动、权限等异常可能,可以在循环内增加异常捕获,避免单次请求失败中断整个采集流程:
all_api_results = [] for auto_sort in response_1: countryname = auto_sort['Country'] iso = auto_sort['ThreeLetterSymbol'] try: current_response = api_call(countryname, iso) all_api_results.extend(current_response) except Exception as e: print(f"采集{countryname}({iso})数据失败:{str(e)}") continue
内容的提问来源于stack exchange,提问作者coderunner84
相关产品推荐
相关产品推荐

