将if-else语句转换为单行的方法

时间:2014-10-30 16:38:00

标签: python

有没有办法在一行上执行以下操作?

if completion.is_anonymous:
    user = 'Anonymous'
else:
    user = completion.user

2 个答案:

答案 0 :(得分:3)

使用三元运算符:

user = 'Anonymous' if completion.is_anonymous else completion.user

答案 1 :(得分:0)

user = "Anonymous" if completion.is_anonymous else completion.user语法:

>>> a = 2 if True else 4
>>> a
2
>>> a = 2 if False else 4
>>> a
4