You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PyPred编写符合语法的Python逻辑判断代码?

PyPred代码修正说明

问题点分析

  • 原需求是精确匹配message等于"How to catch taxi",但你用了contains,不符合预期逻辑;
  • PyPred的Predicate需要结合变量值完成评估,仅传入表达式字符串无法生效;
  • 原逻辑中的country和city被合并为place参数,若该参数确实可代表国家或城市,逻辑方向没问题,但需对齐PyPred语法规范。

修正后的代码

from pypred import Predicate

def taxi_response(place, message):
    # 编写符合PyPred语法的表达式,精确匹配条件
    expr = "(place == 'Russia' or place == 'Moscow') and message == 'How to catch taxi'"
    pred = Predicate(expr)
    
    # 传入变量上下文,评估表达式是否成立
    if pred.test({"place": place, "message": message}):
        return "You can catch taxi here: link"

可选调整(若需区分country和city参数)

如果要严格对应原逻辑中的country和city两个独立参数,代码需调整为:

from pypred import Predicate

def taxi_response(country, city, message):
    expr = "(country == 'Russia' or city == 'Moscow') and message == 'How to catch taxi'"
    pred = Predicate(expr)
    
    if pred.test({"country": country, "city": city, "message": message}):
        return "You can catch taxi here: link"

内容的提问来源于stack exchange,提问作者Роман Свирид

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 23:05:17