I run some code within a for loop. I want to take the results from my loop and place them in a 2d array with 2 columns and as many rows as times I iterate the loop. Here's a simplified version of what I have:
我在for循环中运行一些代码。我想从循环中获取结果并将它们放在一个2列数组中,其中包含2列和多次行迭代循环。这是我的简化版本:
for i in range(10):
'bunch of stuff'
centerx = xc
centery = yc
How can I save my values for centerx
and centery
in a 2d array with 2 columns and 10 rows? Any help is appreciated, thanks!
如何在具有2列和10行的2d数组中保存centerx和centery的值?任何帮助表示赞赏,谢谢!
3 个解决方案
#1
1
You can try this:
你可以试试这个:
import numpy as np
listvals = []
for i in range(10):
listvals.append((xc, yc))
mat_vals = np.vstack(listvals)
This will output an ndarray like this:
这将输出如下的ndarray:
[[ 2 0]
[ 3 1]
[ 4 2]
[ 5 3]
[ 6 4]
[ 7 5]
[ 8 6]
[ 9 7]
[10 8]
[11 9]]
Or this maybe is 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))
#2
1
You can do this:
你可以这样做:
aList = []
for i in range(10):
aList.append([xc, yc])
#3
0
Try this comprehension,
尝试这种理解,
[ [i, i*10] for i in range(5) ]
which delivers
提供
[[0, 0], [1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]
#1
1
You can try this:
你可以试试这个:
import numpy as np
listvals = []
for i in range(10):
listvals.append((xc, yc))
mat_vals = np.vstack(listvals)
This will output an ndarray like this:
这将输出如下的ndarray:
[[ 2 0]
[ 3 1]
[ 4 2]
[ 5 3]
[ 6 4]
[ 7 5]
[ 8 6]
[ 9 7]
[10 8]
[11 9]]
Or this maybe is 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))
#2
1
You can do this:
你可以这样做:
aList = []
for i in range(10):
aList.append([xc, yc])
#3
0
Try this comprehension,
尝试这种理解,
[ [i, i*10] for i in range(5) ]
which delivers
提供
[[0, 0], [1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]