简体   繁体   中英

Storing multiple ndarrays to a list

During each iteration of for loop some results get stored in a ndarray which look like this,

testpredict=[[1.1],
             [2.344],
             [3.00]]

I want to store the above results in a list variable during each iteration. Something like...

list[i]= testpredict

My final list should look like this:

final_list=[
            [[1.1], [2.344], [3.00]], 
            [[4.03130], [4.55914], [4.46367]],
            .......
           ]

how can I do this correctly?

# declared outside the iteration loop
new_list = []

# inside the loop
new_list = new_list.append(testpredict.tolist())

'list' is a built-in type. Avoid using it as a variable name, as a best practice.

For each interation append the testpredict to the final_list:

import numpy as np
final_list= []
testpredict=np.array([[1.1],
             [2.344],
             [3.00]])

final_list.append(testpredict.tolist())

Let's simulate 3 iterations with the same testpredict as a result:

final_list = []
# lets simulate 3 iteration
for iter in [1,2,3]:
    # testpredict would be your result at each iteration
    testpredict = np.array([[1.1],
                   [2.344],
                   [3.00]])
    final_list.append(testpredict.tolist())
print(final_list)

The above solutions are all correct but I just want to point out that if you want to optimize your code and you are sure that all arrays have the same shape you can save everything in another ndarray with a higher dimension.

For example:

newarray = np.empty((nArrays,*array.shape))
for i in range(nArrays):
    newarray [ i, :, :, ... ] = array

In this way you can access every element through the first index of newarray. All the operations will be much faster using numpy and also I'm case of very large arrays the list method can easily eat all the available RAM and it will be much slower since you are appending elements instead of just changing their values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM