本文翻译自:Putting a simple if-then-else statement on one line [duplicate]
Possible Duplicate: 可能重复:
Python Ternary Operator Python三元运算符
I'm just getting into Python and I really like the terseness of the syntax. 我刚刚进入Python,我非常喜欢语法的简洁性。 However, is there an easier way of writing an if
- then
- else
statement so it fits on one line? 但是,是否有更简单的方法来编写if
- then
- else
语句,使其适合一行?
For example: 例如:
if count == N:
count = 0
else:
count = N + 1
Is there a simpler way of writing this? 有没有更简单的写作方式? I mean, in Objective-C I would write this as: 我的意思是,在Objective-C中我会把它写成:
count = count == N ? 0 : count + 1;
Is there something similar for Python? Python有类似的东西吗?
Update 更新
I know that in this instance I can use count == (count + 1) % N
. 我知道在这个例子中我可以使用count == (count + 1) % N
。
I'm asking about the general syntax. 我问的是一般语法。
#1楼
参考:https://stackoom.com/question/Bl7G/在一行上添加一个简单的if-then-else语句-重复
#2楼
Moreover, you can still use the "ordinary" if
syntax and conflate it into one line with a colon. 此外,您仍然可以使用“普通” if
语法,并使用冒号将其合并为一行。
if i > 3: print("We are done.")
or 要么
field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural))
#3楼
That's more specifically a ternary operator expression than an if-then, here's the python syntax 这更像是一个三元运算符表达式而不是if-then,这是python语法
value_when_true if condition else value_when_false
Better Example: (thanks Mr. Burns ) 更好的例子:(感谢伯恩斯先生 )
'Yes' if fruit == 'Apple' else 'No'
Now with assignment and contrast with if syntax 现在使用if语法分配和对比
fruit = 'Apple'
isApple = True if fruit == 'Apple' else False
vs VS
fruit = 'Apple'
isApple = False
if fruit == 'Apple' : isApple = True
#4楼
count = 0 if count == N else N+1
- the ternary operator. - 三元运算符。 Although I'd say your solution is more readable than this. 虽然我说你的解决方案比这更具可读性。
#5楼
General ternary syntax: 一般三元语法:
value_true if <test> else value_false
Another way can be: 另一种方式可以是:
[value_false, value_true][<test>]
eg: 例如:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. 这会在选择之前评估两个分支。 To only evaluate the chosen branch: 仅评估所选分支:
[lambda: value_false, lambda: value_true][<test>]()
eg: 例如:
count = [lambda:0, lambda:N+1][count==N]()
#6楼
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
它会变成你的代码片段,
count = 0 if count == N else N + 1