3 回答

TA贡献1877条经验 获得超1个赞
更确切地说,这是三元运算符而不是if-then,这是python语法
value_when_true if condition else value_when_false
更好的例子:(感谢伯恩斯先生)
'Yes' if fruit == 'Apple' else 'No'
现在具有赋值并与if语法进行对比
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
与
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True

TA贡献1865条经验 获得超7个赞
而且,您仍然可以使用“普通” if语法并将其与冒号合并为一行。
if i > 3: print("We are done.")
要么
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))

TA贡献1858条经验 获得超8个赞
通用三元语法:
value_true if <test> else value_false
另一种方法可以是:
[value_false, value_true][<test>]
例如:
count = [0,N+1][count==N]
这会在选择一个分支之前先评估两个分支。仅评估所选分支:
[lambda: value_false, lambda: value_true][<test>]()
例如:
count = [lambda:0, lambda:N+1][count==N]()
添加回答
举报