简体   繁体   中英

Python, Concise code on if else statement with function call?

I am wondering if there is a more concise code on the below snippet.

def fun(x):
    return x + 2
a = 3
x = fun(a)
m = x if x == 3 else 4

print(m)

Would this work?

def fun(x):
    return x + 2

m = (x = fun(3)) if x == 3 else 4

print(m)

If you're determined to make it a one-liner, and for some reason you can only call fun once, you can use a lambda function:

m = (lambda x: x if x == 3 else 4)(fun(a))

You can see that this isn't terribly readable, and I wouldn't recommend it.

Your trial code wouldn't work because you can't do assignment in an expression.

It can be done, but it's not very readable/maintainable code:

m, = [ x if x == 3 else 4   for x in [fun(a)] ]

The assignment to x persists after it is used as the loop variable inside the list comprehension. Therefore, this one-liner has the effect of assigning both m and x in the way that you want.

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