Python - 如何对由或/和运算符分隔的变量进行分组
我试图找到一种方法使以下(示例)代码更加优雅:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
选项 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.您可以使用 < code>in 运算符 与列表进行比较:
You can use the
in
operator to compare against a list:下面的代码做了同样的事情:
Following code does the same thing: