将 if-elif-else 语句放在一行上? [英] Putting an if-elif-else statement on one line?
问题描述
我已阅读以下链接,但它没有解决我的问题.
Python 有三元条件运算符吗?(问题是关于将 if-else 语句压缩为一行)
是否有更简单的方法来编写 if-elif-else 语句使其适合一行?
例如,
if expression1:声明1elif 表达式2:陈述2别的:声明3
或者一个真实世界的例子:
if i >100:x = 2elif i <100:x = 1别的:x = 0
我只是觉得如果上面的例子可以这样写,它看起来会更简洁.
x=2 if i>100 elif i<100 1 else 0 [错误]
不,这是不可能的(至少不是任意语句),也不可取.将所有内容放在一行上很可能会违反 PEP-8,其中规定行不应超过长度为 80 个字符.
这也违背了 Python 的禅意:可读性很重要".(在 Python 提示符下键入 import this
以阅读整个内容).
你可以在 Python 中使用三元表达式,但只能用于表达式,不能用于语句:
<预><代码>>>>a = "Hello" if foo() else "Goodbye"您修改后的问题现在表明,除了被分配的值之外,这三个语句是相同的.在这种情况下,链接的三元运算符确实有效,但我仍然认为它的可读性较差:
<预><代码>>>>我=100>>>a = 1 if i<100 else 2 if i>100 else 0>>>一个0>>>我=101>>>a = 1 if i<100 else 2 if i>100 else 0>>>一个2>>>我=99>>>a = 1 if i<100 else 2 if i>100 else 0>>>一个1I 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)
Is there an easier way of writing an if-elif-else statement so it fits on one line?
For example,
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]
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-8 where it is mandated that lines should not exceed 80 characters in length.
It's also against the Zen of Python: "Readability counts". (Type import this
at the Python prompt to read the whole thing).
You can use a ternary expression in Python, but only for expressions, not for statements:
>>> 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
这篇关于将 if-elif-else 语句放在一行上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!