【问题标题】:Google Colab: How to loop through data filled in colab forms input?Google Colab:如何遍历 colab 表单输入中填写的数据?
【发布时间】:2021-01-26 01:44:17
【问题描述】:

我创建了this 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)

预期的行为是,在填写一个人的数据并将其添加到对象列表(人)之后,用户将能够更改表单的数据并向其中添加另一个对象。 Ex(在通知 '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

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

【问题讨论】:

    标签: python jupyter-notebook google-colaboratory


    【解决方案1】:

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

    冗长的回答:

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

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

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

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

    解决方法:

    • 使用输入字段(正如您所做的那样)来定义每个类属性(我这样做是为了快速 + 肮脏的修复)
    • 使用ipywidgets - 这是一个很好的资源:@​​987654323@

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

    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')
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2021-08-14
      • 2018-09-15
      相关资源
      最近更新 更多