"walrus operator" 赋值的多个条件

Multiple conditions for "walrus operator" assignment

我想知道是否可以使用 "walrus operator" 根据某些条件以及现有条件来分配值。例如,如果该字符串包含一些子字符串,则将该字符串分配给 post_url

if post_url := data.get("Post url") and ("youtube" in data.get("Post url")):
    # Do something with post_url
else:
    # Do something else

但是,由于对 and 操作的评估,这只是将布尔值分配给 post_url

您可以使用括号将其分组,您甚至不需要重复 data.get:

if (post_url := data.get("Post url")) and "youtube" in post_url:
    # Do something with post_url
else:
    # Do something else

这将为 post_url 分配一个值,因此您可以访问 Noneelse 块中不包含 "youtube" 的 URL .