gpt4 book ai didi

python - 将 for 循环值传递到 API 调用字段

转载 作者:行者123 更新时间:2023-12-01 07:24:10 24 4
gpt4 key购买 nike

我需要从 for 循环中获取多个值并将它们传递给 api 调用。对我来说最好的方法是什么?

引用的值是“id”,我需要它们中的每一个来填充 api 调用中的 id 要求。

*** 我的 for 循环

response = json.loads(z)

for d in response:
for key, value in d['to'].items():
if key == 'id':
print(value)

*** API 调用

id = '' # str |
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )



api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)

最佳答案

正如您自己指出的,您需要一个字符串。所以当你循环它们时,你必须将这些 id 添加到某个字符串中。因此,让我们从创建一个空字符串开始。然后,当我们循环时,我们可以将其连接到字符串

,而不是打印 ID
string = ""
for d in response:
for key, value in d['to'].items():
if key == 'id':
string += value

然后是:

id = string

现在我当然不知道该字符串对于该特定 API 需要采用什么格式。但是您应该能够调整该模式,例如,如果需要,可以用逗号分隔值。

(注意,我使用名称字符串是为了在这个问题的上下文中清楚地表达出来,但显然想出一个更好的变量名称)

编辑:如何进行多个 API 调用

如果每次 API 调用只能发送一个 ID,那么您可以做两件事。也在循环中进行调用,或者将此 ID 保存到列表中。无论哪种情况,如果您将 API 调用包装到函数中都会有所帮助:

def make_api_call(id)
id = id
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )
api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)

现在,您可以像这样在循环中调用它:

for d in response:
for key, value in d['to'].items():
if key == 'id':
make_api_call(value)

或者您可以构建一个列表,然后在该列表上运行调用:

all_ids = []

for d in response:
for key, value in d['to'].items():
if key == 'id':
all_ids.append(value)

for id in all_ids:
make_api_call(id)

(注意,我使用变量名“id”与问题一致。但是“_id”是首选,因为“id”是内置变量。)

关于python - 将 for 循环值传递到 API 调用字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57538099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com