Abi*_*ern 782 python syntax if-statement ternary-operator
可能重复:
Python三元运算符
我刚刚进入Python,我非常喜欢语法的简洁性.然而,有没有写一个更简单的方法if- then- else语句,因此它适合在同一行?
例如:
if count == N:
count = 0
else:
count = N + 1
Run Code Online (Sandbox Code Playgroud)
有没有更简单的写作方式?我的意思是,在Objective-C中我会把它写成:
count = count == N ? 0 : count + 1;
Run Code Online (Sandbox Code Playgroud)
Python有类似的东西吗?
更新
我知道在这种情况下我可以使用count == (count + 1) % N.
我问的是一般语法.
cms*_*sjr 1445
这更像是一个三元运算符表达式而不是if-then,这是python语法
value_when_true if condition else value_when_false
Run Code Online (Sandbox Code Playgroud)
更好的例子:(感谢伯恩斯先生)
'Yes' if fruit == 'Apple' else 'No'
现在使用if语法分配和对比
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
Run Code Online (Sandbox Code Playgroud)
VS
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
Run Code Online (Sandbox Code Playgroud)
小智 161
此外,您仍然可以使用"普通" if语法并将其与冒号分隔成一行.
if i > 3: print("We are done.")
Run Code Online (Sandbox Code Playgroud)
要么
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
Run Code Online (Sandbox Code Playgroud)
Tim*_*ker 123
count = 0 if count == N else N+1
Run Code Online (Sandbox Code Playgroud)
- 三元运算符.虽然我说你的解决方案比这更具可读性.
msh*_*yem 98
一般三元语法:
value_true if <test> else value_false
Run Code Online (Sandbox Code Playgroud)
另一种方式可以是:
[value_false, value_true][<test>]
Run Code Online (Sandbox Code Playgroud)
例如:
count = [0,N+1][count==N]
Run Code Online (Sandbox Code Playgroud)
这会在选择之前评估两个分支.仅评估所选分支:
[lambda: value_false, lambda: value_true][<test>]()
Run Code Online (Sandbox Code Playgroud)
例如:
count = [lambda:0, lambda:N+1][count==N]()
Run Code Online (Sandbox Code Playgroud)
pho*_*x24 20
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
Run Code Online (Sandbox Code Playgroud)
它会变成你的代码片段,
count = 0 if count == N else N + 1
Run Code Online (Sandbox Code Playgroud)