循环调用get_t1_file函数时提示t1_file未定义该如何解决?
问题原因分析
- 你在
get_t1_file函数内部定义的t1_file属于局部变量,作用域仅局限在函数内部,函数执行完成后,外部代码无法直接访问该变量。 - 你调用
get_t1_file(sess)时没有接收函数的返回值:该函数已经通过return语句把匹配到的T1文件对象/None作为结果返回,你没有把返回结果赋值给变量,自然会触发t1_file未定义的报错。 - 你的
get_t1_file函数定义本身没有问题,不需要调整。
修复方案
只需要修改你的遍历代码,接收函数返回值即可:
t1_files = [] for s in session_ids: sess = fw.get(s) # 接收函数返回结果赋值给变量 t1_file = get_t1_file(sess) t1_files.append(t1_file)
如果不需要保留中间变量,可以简化为直接追加返回结果:
t1_files = [] for s in session_ids: sess = fw.get(s) t1_files.append(get_t1_file(sess))
更简洁的写法可以用列表推导式实现:
t1_files = [get_t1_file(fw.get(s)) for s in session_ids]
内容的提问来源于stack exchange,提问作者florence-y
相关产品推荐
相关产品推荐

