简体   繁体   中英

Python one line if-else with different operators

I was fiddling with one line if and for statements in python and ran across the following problem:

I can make something like the following work:

state = 1 if state == 4 else 2

But I want to use = and += in the same context, something like this:

state = 1 if state == 4 else state+=1

How can I implement this in one line?

+= is not an operator, it is a statement . You cannot use statements in an expression.

Since state is an integer, just use + , which is an operator:

state = 1 if state == 4 else state + 1

The end result is exactly the same as having used an += in-place addition.

Better still, use the % modulus operator:

state = (state % 4) + 1

which achieves what you wanted to achieve in the first place; limit state to a value between 1 and 4 .

This is not possible because assignment is not an expression in Python.

Only expressions have a value in Python, which is different from JavaScript for example - where almost anything, including assignments, have a value.

You can write your program like this, however:

state = 1 if state == 4 else state + 1

This makes the value conditional on the state, not the assignment. It works in your case since the state variable is always assigned a new value.

In the general case, let's say you want to update different variables depending on the current state, you should stick to a regular if statement. Don't overuse the ternary operator ( x if C else y ) - only use it if it makes your code more readable.

您已经将结果指定为state因此您可以:

state = 1 if state == 4 else state + 1

Just an alternative way to do this is: var = test and "when true" or "when false"

state = state == 4 and 1 or state + 1

The modulus answer is better for this but the above is useful shortcut

using lambda:

state = (lambda n:[n+1,0][n==4] )(state)

so, in essence:

[n+1,0][1] # True(1): means get index#1, which is 0
[n+1,0][0] # False(0):means get index#0, which is n+1

To make it more readable, I will break it down to a function:

def myfunc(n):
    ans = [ n+1, 0 ]
    if n==4:
        return ans[1] # which is the value 0
    else:
        return ans[0] # which is n+1

state=6
state=myfunc(state) # returns 7
state=4
state=myfunc(state) # returns 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM