将 if-elif-else 语句放在一行上?[重复]
- 2025-02-20 09:22:00
- admin 原创
- 24
问题描述:
有没有更简单的方法可以编写 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]
我已阅读下面的链接,但它并没有解答我的问题。
Python 有三元条件运算符吗?(问题是关于将 if-else 语句压缩为一行)
解决方案 1:
不,这是不可能的(至少对于任意语句来说是不可能的),也不可取。将所有内容放在一行中很可能违反PEP-8,其中规定行的长度不得超过 80 个字符。
这也违背了 Python 的“可读性至上”的原则。(import this
在 Python 提示符下输入即可阅读全文)。
您可以在 Python 中使用三元表达式,但只能用于表达式,不能用于语句:
>>> a = "Hello" if foo() else "Goodbye"
编辑:
现在,您修改后的问题表明,除了赋值之外,这三个语句是相同的。在这种情况下,链式三元运算符确实有效,但我仍然认为它的可读性较差:
>>> i = 100
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
0
>>> i = 101
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
2
>>> i = 99
>>> x = 2 if i>100 else 1 if i<100 else 0
>>> x
1
解决方案 2:
如果您只需要针对不同情况使用不同的表达方式,那么这可能适合您:
expr1 if condition1 else expr2 if condition2 else expr3
例如:
a = "neg" if b<0 else "pos" if b>0 else "zero"
解决方案 3:
尽管还有其他一些答案:是的,这是可能的:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
翻译为以下一行:
statement1 if expression1 else (statement2 if expression2 else statement3)
事实上你可以将它们嵌套到无限远。尽情享受吧 ;)
更新:这就是“真实世界”示例的样子:
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)
所以我最初的回答不够精确,但这个解决方案可以满足 OP 的要求。
解决方案 4:
只需在 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'
解决方案 5:
在我看来,还有一种相当难以理解的替代方案,但出于好奇,我还是想分享一下:
x = (i>100 and 2) or (i<100 and 1) or 0
更多信息请访问:https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
解决方案 6:
您可以选择实际使用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
,则结果似乎不可预测。
解决方案 7:
是的,你可以这样做:
i = int(input('type your num here : '))
x = 2 if i > 100 else ( 1 if i < 100 else 0)
print (x)
解决方案 8:
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 将被分配 1;如果 i = 100,则 x 将被分配 0
解决方案 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
解决方案 10:
人们已经提到了三元表达式。有时以简单的条件赋值为例,可以使用数学表达式来执行条件赋值。这可能不会使您的代码非常易读,但它确实可以在一行相当短的时间内完成。您的示例可以这样写:
x = 2*(i>100) | 1*(i<100)
比较结果为 True 或 False,与数字相乘时结果为 1 或 0。可以在中间使用 + 代替 |。
解决方案 11:
嵌套三元运算符是最好的解决方案——
示例案例 -
4 = 1
3 = 2
2 = 3
1 = 4
a = 4
prio = 4 if a == 1 else (3 if a == 2 else (2 if a == 3 else 1))
解决方案 12:
这也取决于你的表达方式。其他答案中“不要这样做”的一般建议对于通用语句和通用表达非常有效。
但是如果您需要的只是一个“调度”表,比如根据给定选项的值调用不同的函数,您可以将要调用的函数放在字典中。
类似于:
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()
...
解决方案 13:
您可以使用嵌套的三元 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))
解决方案 14:
MESSAGELENGHT = 39
"A normal function call using if elif and else."
if MESSAGELENGHT == 16:
Datapacket = "word"
elif MESSAGELENGHT == 8:
Datapacket = 'byte'
else:
Datapacket = 'bit'
#similarly for a oneliner expresion:
Datapacket = "word" if MESSAGELENGHT == 16 else 'byte' if MESSAGELENGHT == 8 else 'bit'
print(Datapacket)
谢谢