【发布时间】:2022-01-20 12:32:43
【问题描述】:
背景 - 我有一个函数从另一个函数 (api_response = api_call()) 获取 API 响应 (api_response)。 Code Block #1 继续迭代,直到 meta 出现在响应中。一旦meta 在api_response 中,那么Code Block #2 将返回api_response。
问题 - 虽然我的代码正在为 meta 测试 api_response,但我还没有找到一种方法来包括连续调用另一个函数(api_response = api_call() 在我的 while loop 中,它将允许确定meta 何时仍在api_response 中。
功能 -
def unpack_response():
# Code Block # 1
api_response = api_call()
while "meta" not in api_response:
id_value = "id"
res1 = [val[id_value] for key, val in api_response.items() if id_value in val]
id_value = "".join(res1)
percent_value = "percent_complete"
res2 = (tuple(api_response["data"]["attributes"].get("percent_complete", '') for key, val in api_response.items()))
print(f' Your data requested, associated with ID: {id_value} is {res2} complete!')
# Code Block # 2
if "meta" in api_response:
return api_response
unpack_response()
问题 - 有没有人有任何指示,关于我如何将api_response 集成到我的循环中,所以它在每次循环迭代时都会被调用?
【问题讨论】:
-
将调用放入循环中,使用
else,您的函数不会返回任何内容 -
使用海象运算符
-
感谢@MadPhysicist - 我已将函数更正为
return api_response。 Inc. 循环内的调用是有道理的(谢谢)。但是else在哪里发挥作用? -
if not x: ...后跟if x: ...通常更好地表述为if not x: ... else: ...。 -
如果我的回答让事情变得更清楚,请告诉我
标签: python while-loop calling-convention