python - 对 ipython 笔记本中的下拉小部件中的值进行排序

标签 python widget jupyter-notebook

我想使用 IPython Notebook 小部件中存在的下拉小部件。下面显示了一个简单的示例...

from IPython.display import display
from IPython.html    import widgets
import random

genName = lambda : ''.join([chr(random.randint(65, 90)) for i in range(10) ])

testValues = [ genName() for i in range(20) ]
testValues = sorted(testValues)
testValues = dict(zip(testValues, testValues)) # This is not sorted because it is a dict
xx = widgets.DropdownWidget(values=testValues)

display(xx)

现在,要插入到 DropdownWidget 中的值接受一个字典,众所周知,它不是一个排序元素。这样做的问题是,当我们想要创建一个小部件并按一定顺序排列下拉列表中的值时,则无法完成,如上面的示例所示。

在我正在使用的示例中,我创建了一组小部件,允许用户使用下拉小部件选择文件。我希望文件按日期排序。然而,由于添加值的方式(使用字典),我似乎无法有效地做到这一点。

有人知道如何解决这个问题吗?

最佳答案

至少有两个选择:

  1. 使用 OrderedDict 而不是经典字典,例如

    from collections import OrderedDict
    ...
    testValues = OrderedDict(zip(testValues, testValues)) # from your example
    
  2. 如果您不要求选择的值与获取的值不同, 您可以使用列表而不是字典,如下所示 here 。这样,小部件的值始终等于所选文本。你的例子看起来像

    ...
    testValues = [ genName() for i in range(20) ]
    testValues = sorted(testValues)
    xx = widgets.DropdownWidget(values=testValues)
    ...
    

根据您的代码,我假设您使用的是 IPython 2.x。请注意,在 IPython 3.x 中,小部件称为 widgets.Dropdown,关键字 values 现在是 options

关于python - 对 ipython 笔记本中的下拉小部件中的值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29739475/

相关文章:

python - 创建 Python 命令行应用程序

python - 从多季度期间提取季度数据

javascript - 控制台到 Python 日志

gwt 中小部件的 CSS

html - Wordpress "Widgets on Pages"和 "Mailchimp Form"- 样式问题

python - 提高 Jupyter Notebook 中的内联图像质量

pythonnet dll 目录访问被拒绝

android - Android:小部件在设备重新启动时崩溃

python - Jupyter Notebook 和 JupyterLab 有什么区别?

ruby-on-rails - 在 jupyter notebook 中无法使用 iruby 命令