简体   繁体   中英

Is there a cleaner and a shorter way to write this conditional in python?

>>> def accept(d1, d2):
    if somefunc(d1,d2) > 32:
        h = 1
    else:
        h = 0
    return h

Does Python have a ternary conditional operator? doesn't give a solution for a case one want to return a value. A lambda based solution is preferable.

The "return-value scenario" is no different than any other:

return 1 if somefunc(d1, d2) > 32 else 0

If for some reason you want a lambda:

lambda d1, d2: 1 if somefunc(d1, d2) > 32 else 0

Note that a lambda is no different than a function defined with def that returns the same thing. Lambdas are just regular functions.

Or, perhaps trickier,

return int(somefunc(d1, d2) > 32)

Note that int(True) == 1 and int(False) == 0 .

变成lambda (不是显式函数):

accept = lambda d1,d2: 1 if somefunc(d1, d2) > 32 else 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