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

Python中函数返回数组在另一函数使用时提示未定义的解决方法

问题修复方案

你的代码存在三个核心问题导致array未定义的错误:

  1. popt_reader函数打开文件时误用了未定义的popt变量,应当使用传入的filename参数
  2. cleaner函数没有设置数组参数,直接引用array属于非法访问未定义变量
  3. 调用cleaner(array)时,array从未被赋值,必须先通过popt_reader读取文件获取数组

修复后的完整代码:

import codecs
import numpy as np

def popt_reader(filename):
    with codecs.open(filename, 'r', encoding='utf-8') as data_file:
        rows, cols = [int(c) for c in data_file.readline().split() if c.isnumeric()]
        array = np.fromstring(data_file.read(), sep=' ').reshape(rows, cols)
        return array

def cleaner(array):
    out = []
    en_point = 0
    for i in range(1, len(array)):
        if np.all((array[i,1::] == 0)):
            pass
        else:
            out.append(array[i,:])
            en_point += 1
    print(en_point)
    return out  # 可选:返回处理后的结果数组,方便后续使用

# 先读取文件获取数组
data_array = popt_reader("你的目标文件名.txt")  # 替换为实际文件路径和名称
# 再将数组传入cleaner函数处理
cleaner(data_array)

额外提示:

  • 确保代码开头导入了codecs和numpy模块(原代码遗漏了导入语句)
  • 可根据需求保留cleaner的返回值,用于后续业务逻辑

内容的提问来源于stack exchange,提问作者user175924

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:15:10