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

当前回答

不,这是不可能的(至少不是任意的陈述),也不是可取的。将所有内容都放在一行上很可能违反PEP-8,其中要求行长度不能超过80个字符。

这也违背了Python的禅意:“可读性很重要”。(在Python提示符下输入import this来读取全部内容)。

你可以在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

其他回答

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

案例-

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

在我看来,还有一种选择是很难读懂的,但我还是要分享一下,只是出于好奇:

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

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

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

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