gpt4 book ai didi

python - "walrus operator"赋值的多个条件

转载 作者:行者123 更新时间:2023-12-02 00:03:24 25 4
gpt4 key购买 nike

我想知道是否可以使用“海象运算符”根据某些条件以及现有条件来分配值。例如,如果该字符串包含一些子字符串,则将该字符串分配给 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 操作的评估,这只是将 bool 值分配给 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 分配一个值,因此您可以访问 None"youtube" 中不包含 的 URL code>else block 。

关于python - "walrus operator"赋值的多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61460408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com