Creating a 2d array in Python using loop results

I am running some code in a for loop. I want to take the results from my loop and put them in a 2d array with 2 columns and as many rows as I repeat the loop. Here is a simplified version of what I have:

 for i in range(10):

      'bunch of stuff'

      centerx = xc
      centery = yc

How to save values ​​for centerxand centeryin a 2d array with two columns and 10 rows? Any help is appreciated, thanks!

+4
source share
3 answers

You can try the following:

import numpy as np
listvals = []
for i in range(10):
    listvals.append((xc, yc))
mat_vals = np.vstack(listvals)

This will output ndarray as follows:

[[ 2  0]
 [ 3  1]
 [ 4  2]
 [ 5  3]
 [ 6  4]
 [ 7  5]
 [ 8  6]
 [ 9  7]
 [10  8]
 [11  9]]

Or it could be better:

import numpy as np
list_xc = []
list_yc = []
for i in np.arange(10): 
    list_xc.append(xc)
    list_yc.append(yc)
mat_xc = np.asarray(list_xc)
mat_yc = np.asarray(list_yc)
mat_f = np.column_stack((mat_xc, mat_yc))
+1
source

You can do it:

aList = []
for i in range(10):
    aList.append([xc, yc])
+1
source

Try this understanding

[ [i, i*10] for i in range(5) ]

which provides

[[0, 0], [1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]
0
source

Source: https://habr.com/ru/post/1628784/


All Articles