gpt4 book ai didi

widget - 如何使用 IPython Widgets 让一个参数的可能值依赖于另一个参数?

转载 作者:行者123 更新时间:2023-12-02 09:23:31 29 4
gpt4 key购买 nike

假设我在 Python 中有这个简单的函数:

def f(gender, name):
if gender == 'male':
return ranking_male(name)
else:
return ranking_female(name)

其中 gender 属于 ['male', 'female']name 属于 ['Adam', ' John', 'Max', 'Frodo'](如果 gendermale)或 ['Mary', 'Sarah', 'Arwen '](否则)。

我希望将 ipywidgets 中的 interact 应用于此函数 f。通常情况下就可以了

from ipywidgets import interact
interact(f, gender = ('male', 'female'), name = ('Adam', 'John', 'Max', 'Frodo'))

问题在于,name 的允许值现在取决于为 gender 选择的值。

我试图在文档中找到它,但找不到。我认为唯一可能重要的是这用于设置特征变化的动态通知。

    Parameters
----------
handler : callable
A callable that is called when a trait changes. Its
signature should be ``handler(change)``, where ``change```is a
dictionary. The change dictionary at least holds a 'type' key.
* ``type``: the type of notification.
Other keys may be passed depending on the value of 'type'. In the
case where type is 'change', we also have the following keys:
* ``owner`` : the HasTraits instance
* ``old`` : the old value of the modified trait attribute
* ``new`` : the new value of the modified trait attribute
* ``name`` : the name of the modified trait attribute.
names : list, str, All
If names is All, the handler will apply to all traits. If a list
of str, handler will apply to all names in the list. If a
str, the handler will apply just to that name.
type : str, All (default: 'change')
The type of notification to filter by. If equal to All, then all
notifications are passed to the observe handler.

但我不知道该怎么做,也不知道如何解释文档字符串正在谈论的内容。非常感谢任何帮助!

最佳答案

例如,您有汽车的品牌型号,而型号取决于品牌

d = {'Volkswagen' : ['Tiguan', 'Passat', 'Polo', 'Touareg', 'Jetta'], 'Chevrolet' : ['TAHOE', 'CAMARO'] }

brand_widget = Dropdown( options=list(d.keys()),
value='Volkswagen',
description='Brand:',
style=style
)
model_widget = Dropdown( options=d['Volkswagen'],
value=None,
description='Model:',
style=style
)

def on_update_brand_widget(*args):
model_widget.options = d[brand_widget.value]

brand_widget.observe(on_update_brand_widget, 'value')

关于widget - 如何使用 IPython Widgets 让一个参数的可能值依赖于另一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37995341/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com