我正在尝试找到一种方法使以下(示例)代码更加优雅:
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/