python - 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
我如何循环并获取实际的表单填充数据?
解决方案
TL;DR:我无法提供 100% 的答案,但是我怀疑没有观察到表单输入(目前)。还有其他选择(见下文)。
长篇大论的回答:
这是一个老问题,但我一直在尝试使用它来构建工厂模拟,并且可以看到有 600 多名访客,所以希望这有助于澄清问题。
我最好的猜测是笔记本在运行代码单元之前设置了降价参数。所以以下内容:
foo = True
while foo:
foo = False # @param {type: "boolean"}
print(foo)
time.sleep(3)
foo
单元格开始执行后,不会从对表单字段的任何更改中读取值。我发现这些笔记本很有帮助:
- https://colab.research.google.com/github/jupyter-widgets/ipywidgets/blob/master/docs/source/examples/Widget%20Events.ipynb
- https://colab.research.google.com/github/jupyter-widgets/ipywidgets/blob/master/docs/source/examples/Widget%20Asynchronous.ipynb
解决方法:
- 使用输入字段(正如您所做的那样)来定义每个类属性(我这样做是为了快速+脏修复)
- 使用
ipywidgets
- 这是一个很好的资源:https ://colab.research.google.com/github/jupyter-widgets/ipywidgets/blob/master/docs/source/examples/Index.ipynb
关于第二个建议,下面的代码允许用户使用滑块将数字添加到列表中,该列表存储为全局变量并可供其他代码单元使用:
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')
您可以为此添加条件以仅在单击按钮时更新对象的集合。
推荐阅读
- c++ - 使用私有析构函数破坏对象
- python - 服务中的 Python 子进程
- javascript - React - 样式化的组件返回一个 [object Object]
- python - Floyd-Warshall algorithm on GPU using numba
- php - 不要在某个时刻写入 COOKIEFILE
- angular - 我是否正确理解什么是 .subscribe()?(角8)
- haskell - Haskell hdbc-odbc 与 Sybase 数据库的连接仅在使用跟踪功能时才有效
- python - POST Json 请求不起作用。NameError:名称“光标”未定义
- excel - 如何遍历一列单元格并将相邻单元格连接到一个新单元格中?
- azure-web-app-service - 如何在 azure API 中发送文本作为输入并接收情绪或情绪作为响应?