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

标签 python operators

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

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

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

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

你更愿意说:

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

这样做更优雅的方法是什么?

提前致谢!

最佳答案

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

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

选项 3:执行一次:

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

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

关于Python - 如何对由或/和运算符分隔的变量进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415212/

相关文章:

python - 对元组进行子迭代

python - 如何以编程方式在 jenkins 作业配置页面中设置 github repo

c++ - 如何覆盖运算符 <

operators - 具有相同优先级的 Prolog 中缀运算符一个 xfy 和另一个 yfx 具有两个顺序运算符

java - 返回值的三元运算符 - Java/Android

python - 在 python 中,如何检查标准输入流 (sys.stdin) 的结尾并对此做一些特殊的事情

python - Python 函数究竟是如何返回/产生对象的?

python - 为什么转置数据以获得多索引数据帧?

c++ - 为什么 C++ 编译器不定义 operator== 和 operator!=?

c++ - 谁能给我一个 operator= of vector in MSDN 的链接?