在我的回调中,有一个函数。在该函数中,我需要使用random.sample(list, 10)
在循环中每次绘制10个样本。因此,我在random.sample(list, 10)
循环之前的函数中使用random.seed(400)
。
每次运行回调时,样本都不相同。我不知道如何使随机样本相同。感谢
def find_best(df,N_calculation):
random.seed(400)
for n_cal in tnrange(N_calculation):
RISKY_ASSETS = random.sample(stock_list_portfolio, n_assets)
在回调中
@app.callback(
[
Output("portfolio-graph", "figure"),
],
[
Input('run-portfolio','n_clicks')
],
[
State('portfolio-data-year-num-slider','value'),
State('portfolio-opt-calc-log-num-slider','value'),
],
prevent_initial_call=True, # disable output in the first load
)
def change_portfolio(n_clicks,delta_year,n_calculation_log):
RISKY_ASSETS_BEST= find_best(df,N_calculation)
除非每次调用random.sample()
的输入stock_list_portfolio
都不同,否则您所描述的内容应该有效。下面是一个它的工作示例,它将使用sample
和seed
:打印列表中的确定元素集
import random
import dash
from dash import html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(
[
html.Div([html.P(id="paragraph_id", children=["Button not clicked"])]),
html.Button(id="button_id", children="Run smapler"),
]
)
@app.callback(
[Output("paragraph_id", "children")],
[Input("button_id", "n_clicks")],
prevent_initial_call=True,
)
def callback(_):
random.seed(4)
res_list = ""
df= [1,2,3,4,5,6]
for n_cal in range(4):
RISKY_ASSETS = random.sample(df, n_cal)
res_list += f"{RISKY_ASSETS}"
return [res_list]
if __name__ == "__main__":
app.run_server(debug=True)