我定义了一个输出两个数组x和y的函数。我的目标是多次调用这个函数(在本例中为10),并将每个输出存储到一个不同的数组中,这样我就可以为x和y平均每个数组。我已经启动代码10次调用这个函数,如下所示: def myfunction() = myexamplefunction;在这个函数中,我定义了输出数组x和y,并可以显示我的函数填充了这些值。例如,x数组看起来像[0,1,2,1,2,3,4,5,6,7,6,7,8,9,10 ]输出。
Xtotal=[0] #new array that stores all the x values
Ytotal=[0] #new array that stores all the y values
for i in myfunction(range(10)):
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
我也尝试过:
for i in range(10):
myfunction()
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
我已经成功地调用了我的函数10次,但不能让每个输出嵌套在我的新数组中。任何帮助都将不胜感激。我正在为这个特定的项目学习python,所以是的,我肯定我缺少一些非常基本的东西。
发布于 2022-06-14 21:08:27
首先,您必须确保您的函数是返回数组的,例如:
def myfunction():
*
*
return X, Y # <-- this line
然后必须调用此函数并将其结果放入新变量,即:
Xtotal = []
Ytotal = []
for i in range(10):
x, y = myfunction() # <-- this line: put returned arrays X, Y in x, y
Xtotal.append(x) #append the whole x array
Ytotal.append(y) #append the whole y array
发布于 2022-06-14 20:42:54
基本嵌套循环
alist =[]
for i in range(3):
blist = []
for j in range(4):
blist.append(func(i,j))
alist.append(blist)
或
alist = [func(i,j) for j in range(4)] for i in range(3)]
请注意,我的func
接受两个值(标量i
和j
),并返回一些内容,例如数字。结果将是一个数字列表。
您将myfunction
描述为返回两个数组。但是,如果有的话,不要对它的论点(输入)说任何话。
In [12]: def myfunction():
...: return np.arange(3), np.ones((4))
...:
In [15]: alist = []
...: for i in range(3):
...: alist.append(myfunction())
...:
In [16]: alist
Out[16]:
[(array([0, 1, 2]), array([1., 1., 1., 1.])),
(array([0, 1, 2]), array([1., 1., 1., 1.])),
(array([0, 1, 2]), array([1., 1., 1., 1.]))]
这是一个元组列表,每个元组包含该函数生成的2个数组。对于这个结果,有什么是对的,什么是错的?
另一种从许多电话中收集结果的方法:
In [17]: alist = []; blist = []
...: for i in range(3):
...: x,y = myfunction()
...: alist.append(x); blist.append(y)
...:
In [18]: alist
Out[18]: [array([0, 1, 2]), array([0, 1, 2]), array([0, 1, 2])]
In [19]: blist
Out[19]: [array([1., 1., 1., 1.]), array([1., 1., 1., 1.]), array([1., 1., 1., 1.])]
https://stackoverflow.com/questions/72622278
复制相似问题