Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按数组名称追加数组_Python_Arrays_Numpy - Fatal编程技术网

Python 按数组名称追加数组

Python 按数组名称追加数组,python,arrays,numpy,Python,Arrays,Numpy,我正在使用一个函数,它输出大约600个元素长的numpy数组 array = function_output() array.shape # this outputs (600,) 我必须在这个函数中使用大约50个输出。每个输出都是不同的。目标是将这些数组中的每个数组连接到一个列表(或numpy数组)中,然后保存结果 我愚蠢地开始单独标记每个数组,即 array1 = function_output() array2 = function_output() ... 然后我想我可以把它连接成

我正在使用一个函数,它输出大约600个元素长的numpy数组

array = function_output()
array.shape # this outputs (600,)
我必须在这个函数中使用大约50个输出。每个输出都是不同的。目标是将这些数组中的每个数组连接到一个列表(或numpy数组)中,然后保存结果

我愚蠢地开始单独标记每个数组,即

array1 = function_output()
array2 = function_output() 
...
然后我想我可以把它连接成一个列表

list = [array1, array2, array3, ..., array50]
(1) 我不认为一开始有任何办法可以通过命名方案来解决。函数的每个输出都是唯一的,应该适当地标记


(2) 然而,以这种方式定义列表,复制和粘贴,感觉很愚蠢。我是否可以使用“for”语句来迭代变量名

每当您对变量名进行编号时,请考虑改用列表:

output = [function_output() for i in range(50)]
与使用
array1
访问第一个数组不同,您将使用
output[0]
(因为Python使用基于0的索引)

要将数组列表合并为一个NumPy数组,可以使用

array = np.column_stack(output)

array.shape
将是
(600,50)

我不完全确定您的代码是如何设置的,但在我看来,您可以利用python的locals()或globals()方法。例如:

    from random import choice as rc

    #randomly populate the arrays
    array1 = rc(range(20))
    array2 = rc(range(20))
    array3 = rc(range(20))
    array4 = rc(range(20)) 
    array5 = rc(range(20))
    array5 = rc(range(20))

    unwanted_variable1 = rc(range(20))
    unwanted_variable2 = rc(range(20))

    local_variables = locals()
    local_keys = list(local_variables.keys())
    wanted_keys = [i for i in local_keys if i[0:5] == 'array']
    # sort the wanted keys numerically
    current_order = [int(i[5:]) for i in wanted_keys]
    desired_order = current_order.copy()
    desired_order.sort()
    ordered_keys = [wanted_keys[current_order.index(i)] for i in desired_order]

    my_list = [local_variables[i] for i in ordered_keys if i[0:5] == 'array']

我相信这本可以做得更干净一点,但我认为它让人明白了这个想法。

不幸的是,我认为这不管用。我应该在上面说得更清楚些,但是每个函数输出都是唯一的——我必须输入几个参数才能使它正确运行。@ShanZhengYang:输入也应该在一个列表中,或者可能是从某种数据文件流出来的。