Python 中 if/elif 语句的替代方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17881409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's an alternative to if/elif statements in Python?
提问by Stupid.Fat.Cat
My code currently looks something like this:
我的代码目前看起来像这样:
if option1:
...
elif option2:
...
elif option3:
....
so on so forth. And while I'm not displeased with it, I was wondering if there was a better alternative in python. My script is a console based script where I'm using argparser to fetch for what the user needs.
等等等等。虽然我对它并不不满,但我想知道 python 是否有更好的选择。我的脚本是一个基于控制台的脚本,我使用 argparser 来获取用户需要的内容。
采纳答案by Fredrik H??rd
If 'option' can contain 'one', 'two', or 'three', you could do
如果 'option' 可以包含 'one'、'two' 或 'three',你可以这样做
def handle_one():
do_stuff
def handle_two():
do_stuff
def handle_three():
do_stuff
{'one': handle_one,
'two': handle_two,
'three': handle_three}[option]()
回答by nicolas.leblanc
This is the first thing that comes to my mind:
这是我想到的第一件事:
Instead of doing this:
而不是这样做:
if option1:
a = 1
elif oprtion2:
a = 2
elif oprtion3:
a = 3
else:
a = 0
You can do this:
你可以这样做:
a = 1 if option1 else 2 if option 2 else 3 if option3 else 0
For more detail, see: PEP 308: Conditional Expressions!
有关更多详细信息,请参阅:PEP 308:条件表达式!
回答by James Roseman
I'm guessing you're starting Python scripting with a background somewhere else, where a switch
statement would solve your question. As that's not an option in Python, you're looking for another way to do things.
我猜你是从其他地方的背景开始 Python 脚本编写的,在那里一个switch
语句可以解决你的问题。由于这不是 Python 中的一个选项,您正在寻找另一种做事的方式。
Without context, though, you can't really answer this question very well (there are far too many options).
但是,如果没有上下文,您就无法很好地回答这个问题(选项太多了)。
I'll throw in one (somewhat Pythonic) alternative:
我将提出一个(有点 Pythonic)替代方案:
Let's start with an example of where I think you're coming from.
让我们从一个我认为你来自哪里的例子开始。
def add_to_x (x):
if x == 3:
x += 2
elif x == 4:
x += 4
elif x == 5:
x += 5
return x
Here's my alternative:
这是我的替代方案:
def add_to_x (x):
vals = { 3 : 5 , 4 : 8 , 5 : 10 }
return vals[x]
You can also look into lambdaswhich you can put into the dictionary structure I used.
您还可以查看可以放入我使用的字典结构中的lambda。
But again, as said, without context this may not be what you're looking for.
但是,如前所述,如果没有上下文,这可能不是您要查找的内容。