问题:将if-elif-else语句放在一行上吗?
我已阅读以下链接,但未解决我的问题。
Python是否具有三元条件运算符?(问题是将if-else语句压缩到一行)
有没有更简单的方式编写if-elif-else语句,使其适合一行?
例如,
if expression1:
statement1
elif expression2:
statement2
else:
statement3
或一个真实的例子:
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
我只是觉得,如果上面的示例可以用以下方式编写,则看起来会更加简洁。
x=2 if i>100 elif i<100 1 else 0 [WRONG]
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]
回答 0
不,这是不可能的(至少不能使用任意语句),也不是可取的。将所有内容都放在一行中很可能会违反PEP-8,在这种情况下,行的长度不得超过80个字符。
这也与Python的Zen背道而驰:“可读性很重要”。(import this
在Python提示符下键入以读取整个内容)。
您可以在Python中使用三元表达式,但只能用于表达式,不能用于语句:
>>> a = "Hello" if foo() else "Goodbye"
编辑:
现在,您修改后的问题表明,除了要分配的值之外,这三个语句是相同的。在这种情况下,链式三元运算符确实可以工作,但是我仍然认为它的可读性较差:
>>> 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
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
回答 1
如果您仅在不同情况下需要不同的表达式,那么这可能对您有用:
expr1 if condition1 else expr2 if condition2 else expr
例如:
a = "neg" if b<0 else "pos" if b>0 else "zero"
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"
回答 2
只需在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'
Just nest another if clause in the else statement. But that doesn’t make it look any prettier.
>>> 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'
回答 3
尽管有其他一些答案:是的,这是可能的:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
转换为以下一种衬纸:
statement1 if expression1 else (statement2 if expression2 else statement3)
实际上,您可以将它们嵌套到无限远。请享用 ;)
Despite some other answers: YES it IS possible:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
translates to the following one liner:
statement1 if expression1 else (statement2 if expression2 else statement3)
in fact you can nest those till infinity. Enjoy ;)
回答 4
您可以选择实际使用a的get
方法dict
:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
get
如果其中一个键可以保证计算为,则不需要该方法True
:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
理想情况下,最多不应将其中一个键评估为True
。如果一个以上的键计算为True
,则结果似乎不可预测。
You can optionally actually use the get
method of a dict
:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don’t need the get
method if one of the keys is guaranteed to evaluate to 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.
回答 5
回答 6
if i > 100:
x = 2
elif i < 100:
x = 1
else:
x = 0
如果要在一行中使用上述代码,则可以使用以下代码:
x = 2 if i > 100 else 1 if i < 100 else 0
这样做时,如果i> 100,x将被分配为2;如果i <100,则x将被分配;如果i = 100,则x将被分配为0。
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
回答 7
这也取决于您的表情的性质。关于“不做”的其他答案的一般建议对于通用语句和通用表达式非常有效。
但是,如果您只需要一个“ dispatch”表(例如,根据给定选项的值调用一个不同的函数),则可以将这些函数放在字典中进行调用。
就像是:
def save():
...
def edit():
...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}
option = get_input()
result = options[option]()
代替if-else:
if option=="save":
save()
...
It also depends on the 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 “dispatch” table, like, calling a different function depending on the value of a given option, you can put the functions to call inside a dictionary.
Something like:
def save():
...
def edit():
...
options = {"save": save, "edit": edit, "remove": lambda : "Not Implemented"}
option = get_input()
result = options[option]()
Instead of an if-else:
if option=="save":
save()
...
回答 8
人们已经提到了三元表达式。有时,以简单的条件分配为例,可以使用数学表达式执行条件分配。这可能不会使您的代码具有很高的可读性,但是确实可以将它放在很短的一行上。您的示例可以这样写:
x = 2*(i>100) | 1*(i<100)
比较将为True或False,然后与数字相乘将为1或0。可以使用+而不是| 在中间。
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.
回答 9
在三元运算符是一个简洁的表达的最好方式。语法为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
The ternary operator is 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:
i = 23 # set any value for i
x = 2 if i > 100 else 1 if i < 100 else 0
回答 10
您可以使用嵌套三元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))
You can use nested ternary if statements.
# 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))
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。