【发布时间】:2018-04-16 14:04:44
【问题描述】:
假设我有一个函数,它接受参数列表。列表可以是可变长度的,并且功能可以。例如:
import math
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
%matplotlib inline
def PlotSuperposition(weights):
def f(x):
y = 0
for i, weight in enumerate(weights):
if i==0:
y+=weight
else:
y += weight*math.sin(x*i)
return y
vf = np.vectorize(f)
xx = np.arange(0,6,0.1)
plt.plot(xx, vf(xx))
plt.gca().set_ylim(-5,5)
PlotSuperposition([1,1,2])
表演
我可以硬编码给定数量的参数交互,就像这里
interact(lambda w0, w1, w2: PlotSuperposition([w0,w1,w2]), w0=(-3,+3,0.1), w1=(-3,+3,0.1), w2=(-3,+3,0.1))
显示
但是我怎样才能以编程方式定义滑块的数量?
我试过了
n_weights=10
weight_sliders = [widgets.FloatSlider(
value=0,
min=-10.0,
max=10.0,
step=0.1,
description='w%d' % i,
disabled=False,
continuous_update=False,
orientation='horizontal',
readout=True,
readout_format='.1f',
) for i in range(n_weights)]
interact(PlotSuperposition, weights=weight_sliders)
但出现错误
TypeError: 'FloatSlider' object is not iterable
在PlotSuperposition 内部说,interact 不会将值列表传递给函数。
如何实现?
【问题讨论】:
标签: python jupyter-notebook ipython-notebook interactive