1

I am working with a function which outputs a numpy array around 600 elements long.

array = function_output()
array.shape # this outputs (600,)

I have to work with around 50 outputs this function. Each output is distinct. The goal is to concatenate each of these arrays together into a list (or numpy array) and then save the results.

I foolishly began labeling each array individually, i.e.

array1 = function_output()
array2 = function_output() 
...

and I then thought I could concatenate this into a list, i.e.

list = [array1, array2, array3, ..., array50]

(1) I don't think there's any way around by naming scheme at first. Each output of the function is unique and should be labeled appropriately

(2) however, it feels foolish to define a list this way, copying and pasting. Could I somehow use a 'for' statement to iterate over variable names?

2 Answers 2

3

Whenever you have numbered variable names, think of using a list instead:

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

Instead of accessing the first array with array1 you would use output[0] instead (since Python uses 0-based indexing.)

To combine the list of arrays into one NumPy array you could then use

array = np.column_stack(output)

array.shape would then be (600, 50).

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, I don't think that works. I should make it clearer above, but each function output is unique---I have to input several parameters in order for it to run correctly.
@ShanZhengYang: The inputs should also be in a list, or perhaps streamed from a data file of some sort.
0

I'm not entirely sure how your code is set up, but it seems to me you could take advantage of python's locals() or globals() methods. For example:

    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']

I'm sure this could have been done a little bit cleaner but I think it gets the idea across.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.