将if-elif-else语句放在一行上吗? [英] Putting an if-elif-else statement on one line?

查看:377
本文介绍了将if-elif-else语句放在一行上吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读下面的链接,但未解决我的问题.
Python是否具有三元条件运算符?(问题在于将if-else语句压缩到一行)

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)

是否有一种更简单的方式来编写if-elif-else语句,使其适合一行?
例如,

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

或真实示例:

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]

推荐答案

不,这是不可能的(至少不是使用任意语句),也不是可取的.将所有内容放到同一行上很可能会违反 PEP-8 ,在此情况下,行数不得超过长度为80个字符.

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.

这也与Python的Zen背道而驰:可读性很重要". (在Python提示符下输入import this以读取全部内容.

It's also against the Zen of Python: "Readability counts". (Type import this at the Python prompt to read the whole thing).

可以在Python中使用三元表达式,但只能用于表达式,不能用于语句:

You can use a ternary expression in Python, but only for expressions, not for statements:

>>> a = "Hello" if foo() else "Goodbye"

您修改后的问题现在表明,除了要分配的值之外,这三个语句是相同的.在这种情况下,链式三元运算符确实可以工作,但我仍然认为它的可读性较差:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆