我已经阅读了下面的链接,但它并没有解决我的问题。 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]

当前回答

人们已经提到过三元表达式。有时,以简单的条件赋值为例,可以使用数学表达式来执行条件赋值。这可能不会使您的代码非常易读,但它确实可以在相当短的一行中得到它。你的例子可以这样写:

x = 2*(i>100) | 1*(i<100)

比较将为True或False,当与数字相乘时,则为1或0。可以用+来代替中间的|。

其他回答

尽管有一些其他的答案:是的,这是可能的:

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

在这样做时,如果i > 100, x将被分配2,如果i < 100, 1,如果i = 100,则为0

可以使用嵌套的三元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))

嵌套三元运算符是最好的解决方案——

案例-

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))
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)

谢谢