繁体   English   中英

Google Colab:如何遍历在 colab 表单输入中填写的数据?

[英]Google Colab: How to loop through data filled in colab forms input?

我创建了这个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

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

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

冗长的答案:

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

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

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

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

解决方法:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM