首页 > 解决方案 > 如何理解这个相等和赋值语句的逻辑?

问题描述

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'。那正确吗?

标签: python

解决方案


这是括号所在的位置:

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 中。==是布尔比较运算符,将返回Trueor False。之后,and就像您期望的那样工作:

| condition1 | condition2 | is_new_user |
| ---------- | ---------- | ----------- |
| True       | True       | True        |
| True       | False      | False       |
| False      | True       | False       |
| False      | False      | False       |

推荐阅读