python - 如何理解这个相等和赋值语句的逻辑?
问题描述
intent = tracker.latest_message["intent"].get("name")
user_type = next(tracker.get_latest_entity_values("user_type"), None)
is_new_user = intent == "how_to_get_started" and user_type == "new"
if intent == "affirm" or is_new_user:
return [SlotSet("onboarding", True)]
elif intent == "deny":
return [SlotSet("onboarding", False)]
return []
在上面的代码中,如何理解这一行:
is_new_user = intent == "how_to_get_started" and user_type == "new"
是否意味着:
if "intent == "how_to_get_started" and user_type == "new" "
,这将返回 True 或 False,然后将此 bool 分配给 'is_new_user'。那正确吗?
解决方案
这是括号所在的位置:
is_new_user = ((intent == "how_to_get_started") and (user_type == "new"))
如果我们想要更详细地说明,我们可以将它们分成三个语句:
condition1 = (intent == "how_to_get_started")
condition2 = (user_type == "new")
is_new_user = (condition1 and condition2)
这是基本的布尔代数,但放入 python 中。==
是布尔比较运算符,将返回True
or False
。之后,and
就像您期望的那样工作:
| condition1 | condition2 | is_new_user |
| ---------- | ---------- | ----------- |
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
推荐阅读
- javascript - 登录后如何让nodejs读取同一文件夹中的另一个文件
- vba - SAP HANA 从 excel VBA 获取数据,使用 excel 数据与 SAP 合作的不同选项
- ios - playinline 不适用于 iOS 上的视频?
- ansible - 使用 Netbox Ansible 模块
- javascript - 是否可以添加一个通过 for 循环迭代的加载更多按钮?
- c# - 在公共交通中使用 Autofac 向消费者注入依赖项
- javascript - 使用 Selenium 和 Python 获取刷新的 Highcharts 数据
- google-chrome - 如何预安装 Google Chrome 扩展程序
- c# - 通过 Github 中的查询参数弃用 API 身份验证
- html - 关于html中项目的想法