Python 将 if-elif-else 语句放在一行上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14029245/
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
Putting an if-elif-else statement on one line?
提问by Matt Elson
I have read the links below, but it doesn't address my question.
Does Python have a ternary conditional operator?(the question is about condensing if-else statement to one line)
我已经阅读了下面的链接,但它没有解决我的问题。
Python 有三元条件运算符吗?(问题是关于将 if-else 语句压缩为一行)
Is there an easier way of writing an if-elif-else statement so it fits on one line?
For example,
是否有一种更简单的方法来编写 if-elif-else 语句使其适合一行?
例如,
if expression1:
statement1
elif expression2:
statement2
else:
statement3
Or a real-world example:
或者一个真实世界的例子:
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
I just feel if the example above could be written the following way, it could look like more concise.
我只是觉得如果上面的例子可以这样写,它看起来会更简洁。
x=2 if i>100 elif i<100 1 else 0 [WRONG]
采纳答案by Tim Pietzcker
No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8where it is mandated that lines should not exceed 80 characters in length.
不,这是不可能的(至少不是任意声明),也不可取。将所有内容放在一行上很可能会违反PEP-8,其中规定行的长度不应超过 80 个字符。
It's also against the Zen of Python: "Readability counts". (Type import thisat the Python prompt to read the whole thing).
这也违背了 Python 的禅宗:“可读性很重要”。(import this在 Python 提示符下键入以阅读整个内容)。
You canuse a ternary expression in Python, but only for expressions, not for statements:
您可以在 Python 中使用三元表达式,但只能用于表达式,不能用于语句:
>>> a = "Hello" if foo() else "Goodbye"
Edit:
编辑:
Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:
您修改后的问题现在表明,除了被分配的值之外,这三个语句是相同的。在这种情况下,链接的三元运算符确实有效,但我仍然认为它的可读性较差:
>>> i=100
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
2
>>> i=99
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
1
回答by Lycha
If you only need different expressions for different cases then this may work for you:
如果您只需要针对不同情况使用不同的表达式,那么这可能适合您:
expr1 if condition1 else expr2 if condition2 else expr
For example:
例如:
a = "neg" if b<0 else "pos" if b>0 else "zero"
回答by David Lai
Just nest another if clause in the else statement. But that doesn't make it look any prettier.
只需在 else 语句中嵌套另一个 if 子句。但这并不使它看起来更漂亮。
>>> x=5
>>> x if x>0 else ("zero" if x==0 else "invalid value")
5
>>> x = 0
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'zero'
>>> x = -1
>>> x if x>0 else ("zero" if x==0 else "invalid value")
'invalid value'
回答by jsbueno
It also depends on teh nature of your expressions. The general advice on the other answers of "not doing it" is quite valid for generic statements and generic expressions.
这也取决于你的表达的性质。关于“不做”的其他答案的一般建议对于通用语句和通用表达式非常有效。
But if all you need is a "dispacth" table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.
但是,如果您只需要一个“dispacth”表,例如根据给定选项的值调用不同的函数,则可以将要调用的函数放在字典中。
Something like:
就像是:
def save():
...
def edit():
...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}
option = get_input()
result = options[option]()
(that instead of
(而不是
if option=="save":
save()
...
)
)
回答by Ant6n
People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:
人们已经提到了三元表达式。有时以简单的条件赋值为例,可以使用数学表达式来执行条件赋值。这可能不会使您的代码非常易读,但它确实可以在相当短的一行中完成。你的例子可以这样写:
x = 2*(i>100) | 1*(i<100)
The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.
比较结果为 True 或 False,与数字相乘时为 1 或 0。可以使用 + 而不是 | 在中间。
回答by Ariel
There's an alternative that's quite unreadable in my opinion but I'll share anyway just as a curiosity:
在我看来,有一个替代方案是完全不可读的,但无论如何我都会出于好奇与大家分享:
x = (i>100 and 2) or (i<100 and 1) or 0
More info here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
更多信息:https: //docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
回答by Shane
You can optionally actually use the getmethod of a dict:
您可以选择实际使用 a 的get方法dict:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don't need the getmethod if one of the keys is guaranteed to evaluate to True:
你并不需要get,如果关键之一是保证评估的方法True:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
At most one of the keys should ideally evaluate to True. If more than one key evaluates to True, the results could seem unpredictable.
理想情况下,至多其中一个键应评估为True。如果多个键的计算True结果为,则结果似乎不可预测。
回答by k0L1081
You can use nested ternary if statements.
您可以使用嵌套的三元 if 语句。
# if-else ternary construct
country_code = 'USA'
is_USA = True if country_code == 'USA' else False
print('is_USA:', is_USA)
# if-elif-else ternary construct
# Create function to avoid repeating code.
def get_age_category_name(age):
age_category_name = 'Young' if age <= 40 else ('Middle Aged' if age > 40 and age <= 65 else 'Senior')
return age_category_name
print(get_age_category_name(25))
print(get_age_category_name(50))
print(get_age_category_name(75))
回答by roshanpoudel
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
If you want to use the above-mentioned code in one line, you can use the following:
如果要在一行中使用上述代码,可以使用以下代码:
x = 2 if i > 100 else 1 if i < 100 else 0
On doing so, x will be assigned 2 if i > 100, 1 if i < 100 and 0 if i = 100
这样做时,如果 i > 100,则 x 将被赋值为 2,如果 i < 100,则赋值为 1,如果 i = 100,则赋值为 0
回答by yoelvis
The ternary operatoris the best way to a concise expression. The syntax is variable = value_1 if condition else value_2. So, for your example, you must apply the ternary operator twice:
在三元运算符是一个简洁的表达的最好方式。语法是variable = value_1 if condition else value_2. 因此,对于您的示例,您必须两次应用三元运算符:
i = 23 # set any value for i
x = 2 if i > 100 else 1 if i < 100 else 0

