【问题标题】:Using a returned array in another function在另一个函数中使用返回的数组
【发布时间】:2023-01-19 14:55:17
【问题描述】:

我有一个函数返回一个数组,第二个函数应该使用这个返回的数组,但程序返回说数组未定义。我该如何解决这个问题?

def popt_reader(filename):
    with codecs.open(popt, '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():
    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)

cleaner(array)

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您永远不会调用返回数组的函数。试试这个,只需输入您自己的文件名

    ...
    
    filename = "my_array_file_here.array"
    array = popt_reader(filename)
    cleaner(array)
    

    【讨论】:

      【解决方案2】:

      变量arraypopt_reader函数中定义,在cleaner函数中不可访问。

      cleaner(array) 之前添加这行代码以使其工作:

      array = popt_reader(filename)
      

      这会将 popt_reader 方法的输出分配给 array 变量。

      请注意,文件名也应事先定义

      filename = "path to file"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-15
        • 2017-03-29
        • 2017-04-03
        • 2014-07-13
        • 2015-02-03
        相关资源
        最近更新 更多