将 if

编程入门 行业动态 更新时间:2024-10-09 09:12:08
本文介绍了将 if-elif-else 语句放在一行上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已阅读以下链接,但它没有解决我的问题.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 i100 else 0>>>一个0>>>我=101>>>a = 1 if i100 else 0>>>一个2>>>我=99>>>a = 1 if i100 else 0>>>一个1

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)

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

本文发布于:2023-07-09 10:36:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085654.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!