按数组名称追加数组

时间:2015-11-30 22:43:46

标签: python arrays numpy

我正在使用一个函数,它输出一个长约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'语句迭代变量名称吗?

2 个答案:

答案 0 :(得分:3)

无论何时编号变量名称,都要考虑使用列表:

output = [function_output() for i in range(50)]

而不是使用array1访问第一个数组,而是使用output[0]代替(因为Python使用基于0的索引。)

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

array = np.column_stack(output)

array.shape将为(600, 50)

答案 1 :(得分:0)

我不完全确定您的代码是如何设置的,但在我看来,您可以利用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']

我确信这可以做得更干净但我认为它可以解决这个问题。