Python - 如何对由或/和运算符分隔的变量进行分组

发布于 2024-10-25 07:01:44 字数 331 浏览 2 评论 0原文

我试图找到一种方法使以下(示例)代码更加优雅:

if answer == "yes" or "Yes" or "Y" or "y" or "why not":
    print("yeah")

以同样的方式,在英语中你不会说:

可能的答案是“是”、“是”、“是”或“为什么不”。

而你更愿意说:

可能的答案是“是”、“是”、“是”或“为什么不”。

更优雅的方法是什么?

提前致谢!!

I am trying to find a way to make the following (sample) code more elegant:

if answer == "yes" or "Yes" or "Y" or "y" or "why not":
    print("yeah")

In the same manner there in english you would not say:

The possible answers are yes or Yes or Y or why not.

and you would rather say:

The possible answers are yes, Yes, Y or why not.

What would the more elegant way of doing this would be?

Thanks in advance!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

还给你自由 2024-11-01 07:01:44

选项 1:回答 ["yes", "Yes", "Y", "y", "why not"] ...这不是一个好主意,每次运行时都会构建一个列表。

选项 2:回答 ("yes", "Yes", "Y", "y", "why not") ...更好的主意,(常量,不可变)元组构建于编译时间。

选项 3:执行一次:

allowables = set(["yes", "Yes", "Y", "y", "why not"])

,然后使用 answer in alloweds 每次你需要它的时候。当允许值的数量很大或者允许值集可能在运行时发生变化时,这是最佳方法。

Option 1: answer in ["yes", "Yes", "Y", "y", "why not"] ... not a good idea, builds a list each time you run it.

Option 2: answer in ("yes", "Yes", "Y", "y", "why not") ... better idea, the (constant, immutable) tuple is built at compile time.

Option 3: do this once:

allowables = set(["yes", "Yes", "Y", "y", "why not"])

and then use answer in allowables each time you need it. This is the best approach when the number of allowable values is large, or the set of allowable values can vary at run-time.

长亭外,古道边 2024-11-01 07:01:44

您可以使用 < code>in 运算符 与列表进行比较:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print("yeah")

You can use the in operator to compare against a list:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print("yeah")
她如夕阳 2024-11-01 07:01:44

下面的代码做了同样的事情:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print "yeah"

Following code does the same thing:

if answer in ["yes", "Yes", "Y", "y", "why not"]:
    print "yeah"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文