[英]How to add the output of a for loop inside a for loop to a list of lists? Python
I am trying to output the result of (Monte Carlo paths) calculations done in a for loop inside a for loop to a list of lists.我正在尝试 output 将在 for 循环内的 for 循环中完成的(蒙特卡洛路径)计算结果转换为列表列表。 However, I only get one list.
但是,我只得到一份清单。 I have indicated below several things I tried.
我在下面指出了我尝试过的几件事。
The result I get is: [path1]
我得到的结果是:
[path1]
What I expect is: [[path1], [path2], ..., [path100]]
Where every path
should be a list of steps
values starting at s0
.我期望的是:
[[path1], [path2], ..., [path100]]
其中每条path
都应该是从s0
开始的steps
值列表。
Any suggestions?有什么建议么?
num_reps = 100
s0 = 10
steps = 6
def func(num_reps, s0, steps):
for j in range(num_reps):
paths = [s0]
st = s0
for i in range(int(steps)):
st = st*np.random.normal(0, 1)
# paths.append(st)
# paths.append([st])
# paths = steps[steps.index(i):]
return paths
return ''
a = func(num_reps, s0, steps)
What you need to do is generate a single path in the inner loop, and then append that to the list of paths in the outer loop, returning that list at the end of the function:您需要做的是在内循环中生成单个路径,然后将 append 生成到外循环中的路径列表,在 function 末尾返回该列表:
import numpy as np
num_reps = 100
s0 = 10
steps = 6
def func(num_reps, s0, steps):
paths = []
for j in range(num_reps):
path = [s0]
st = s0
for i in range(int(steps)):
st = st*np.random.normal(0, 1)
path.append(st)
paths.append(path)
return paths
a = func(num_reps, s0, steps)
print(a)
Sample output:样品 output:
[
[10, -16.032722636966014, 3.7409928347961676, 2.627699221438861, 0.028916747229045144, 0.018945060221139155, 0.012497699758698825],
[10, 10.900456668192026, 10.821821167576429, 11.673219600653663, 8.739058453116968, 11.597769227413888, 5.365291250490312],
... 98 more ...
]
You can use 'yield' and write a generator您可以使用'yield'并编写一个生成器
def path_generator(num_reps, s0, steps):
for j in range(num_reps):
path = [s0]
st = s0
for i in range(int(steps)):
st = st*np.random.normal(0, 1)
path.append(st)
yield path
for path in path_generator(num_reps, s0, steps):
print path
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.