A = 200
B = -140
C = 400
D = -260
if A < 0:
v1 = 0
else:
v1 = A
if B < 0:
v2 = 0
else:
v2 = B
if C < 0:
v3 = 0
else:
v3 = C
if D < 0:
v4 = 0
else:
v4 = C
What is the shorthand implementation for the above code structure.? Is there a better / elegant / convenient way to do this?
A = 200
B = -140
C = 400
D = -260
v1, v2, v3, v4 = [x if x > 0 else 0 for x in (A, B, C, D)]
If you prefer to use the max
function to the python ternary operator, it would look like:
v1, v2, v3, v4 = [max(x, 0) for x in (A, B, C, D)]
However, if you're planning on having all of these variables treated the same, you might want to consider putting them in a list/tuple in the first place.
values = [200, -140, 400, -260]
values = [max(x, 0) for x in values]
This can be solved easily by using the max()
builtin and unpacking a list comprehension.
v1, v2, v3, v4 = [max(x, 0) for x in [a, b, c, d]]
An alternative solution is to use the map()
function - this is, however, less readable:
v1, v2, v3, v4 = map(lambda x: max(x,0), [a, b, c, d])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With