You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的testFunction中使用unidades函数生成的id列表

解决方法

有几种常用方式可以让testFunction拿到unidades生成的id列表,最推荐的是返回值传递,这也是Python函数间传递数据的标准做法:

方法1:返回id列表并作为参数传递

修改unidades函数让它返回生成的id列表,然后在调用环节把这个列表传给testFunction:

import requests 

def Sults():
  headers = {
        "xxxxxxxxxxxxx",
        "Content-Type":"application/json;charset=UTF-8"
    } 
  url = "https://xxxxxxxxx/api/v1/implantacao/projeto?&dtInicio=2022-08-06T18:02:55Z"
  response = requests.get(url, headers=headers)
  data = response.json() 
  
  print(data) 
  # 接收unidades返回的id列表
  project_ids = unidades(data)
  # 把id列表传给testFunction
  testFunction(project_ids)


def unidades(data):
  id = []
  
  for i in data['data']:
    print(i['nome'])
    print(i['dtInicio'])
    print(i['dtFim'])
    id.append(i['id'])
    print(i['responsavel']['nome'])
    print(i['modelo']) 
  # 返回生成的id列表
  return id

def testFunction(ids):
  # 这里就可以使用传入的ids列表了
  print("拿到的id列表:", ids)
  # 后续业务逻辑写在这里

方法2:使用全局变量(不推荐)

如果不想调整函数调用关系,可以用全局变量存储id列表,但这种方式会增加代码耦合度、降低可维护性,仅适合简单场景:

import requests 

# 定义全局变量存储id列表
project_ids = []

def Sults():
  headers = {
        "xxxxxxxxxxxxx",
        "Content-Type":"application/json;charset=UTF-8"
    } 
  url = "https://xxxxxxxxx/api/v1/implantacao/projeto?&dtInicio=2022-08-06T18:02:55Z"
  response = requests.get(url, headers=headers)
  data = response.json() 
  
  print(data) 
  unidades(data)
  testFunction()


def unidades(data):
  global project_ids  # 声明使用全局变量
  project_ids.clear()  # 先清空避免旧数据干扰
  
  for i in data['data']:
    print(i['nome'])
    print(i['dtInicio'])
    print(i['dtFim'])
    project_ids.append(i['id'])
    print(i['responsavel']['nome'])
    print(i['modelo']) 

def testFunction():
  # 直接使用全局变量里的id列表
  print("拿到的id列表:", project_ids)

优先推荐方法1,它遵循函数单一职责原则,代码逻辑更清晰、易维护。

内容的提问来源于stack exchange,提问作者Henrique Mazetti Ferraz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:30:48