首页 > 解决方案 > Google Colab:如何遍历 colab 表单输入中填写的数据?

问题描述

我创建了这个Google Colab 笔记本来从表单输入中获取用户数据:

there_is_more_people = True
people = []

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age


def register_people(there_is_more_people):
  while there_is_more_people:
    did_you_finish = input("did you finish filling the fields? y/n")[0].lower()
    #@markdown ## Fill your data here:
    name = "mary" #@param {type:"string"}
    age =  21#@param {type:"integer"}
    new_person = Person(name, age)
    people.append(new_person)
    if did_you_finish == 'y':
      people.append(new_person)
      input_there_is_more_people = input("there is more people? y/n")[0].lower()
      if input_there_is_more_people == 'y':
        there_is_more_people = True
        name = None
        age = None
      else: 
        there_is_more_people = False
  for i in people:
    print("These are the people you registered:")
    print(i.name)

register_people(there_is_more_people)

预期的行为是,在填写一个人的数据并将其添加到对象列表(人)之后,用户将能够更改表单的数据并向其中添加另一个对象。前(在通知 'mary', 21 e 'john', 20 之后):

      print("These are the people you registered:")
      for i in people:
        print(i.name, i.age)

These are the people you registered:
mary, 21
john, 20

但是,即使修改输入数据:

    #@markdown ## Fill your data here:
    name = "mary" #@param {type:"string"}
    age =  21#@param {type:"integer"}

    #@markdown ## Fill your data here:
    name = "john" #@param {type:"string"}
    age =  20#@param {type:"integer"}

我只得到单元格开始执行时表单上的值:

These are the people you registered:
mary, 21
mary, 21

我如何循环并获取实际的表单填充数据?

标签: pythonjupyter-notebookgoogle-colaboratory

解决方案


TL;DR:我无法提供 100% 的答案,但是我怀疑没有观察到表单输入(目前)。还有其他选择(见下文)。

长篇大论的回答:

这是一个老问题,但我一直在尝试使用它来构建工厂模拟,并且可以看到有 600 多名访客,所以希望这有助于澄清问题。

我最好的猜测是笔记本在运行代码单元之前设置了降价参数。所以以下内容:

foo = True
while foo:
  foo = False # @param {type: "boolean"}
  print(foo)
  time.sleep(3)

foo单元格开始执行后,不会从对表单字段的任何更改中读取值。我发现这些笔记本很有帮助:

解决方法:

关于第二个建议,下面的代码允许用户使用滑块将数字添加到列表中,该列表存储为全局变量并可供其他代码单元使用:

import ipywidgets as widgets
from IPython.display import display
int_range = widgets.IntSlider()
output2 = widgets.Output()
list1 = []

display(int_range, output2)

def on_value_change(change):
   with output2:
       list1.append(change['new'])
       print(change['new'], list1)

int_range.observe(on_value_change, names='value')

您可以为此添加条件以仅在单击按钮时更新对象的集合。


推荐阅读