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

当前回答

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

其他回答

这也取决于你表达的性质。关于“不这样做”的其他答案的一般性建议对于一般的语句和一般的表达是相当有效的。

但如果你所需要的只是一个“分派”表,比如,根据给定选项的值调用不同的函数,你可以把要调用的函数放在字典中。

喜欢的东西:

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

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

你可以选择使用dict的get方法:

x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)

如果保证其中一个键的值为True,则不需要get方法:

x = {i<0: -1, i==0: 0, i>0: 1}[True]

理想情况下,最多只有一个键值为True。如果有多个键的值为True,则结果似乎不可预测。

只需在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'

三元运算符是实现简洁表达式的最佳方式。语法为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