Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if multple variables greater than zero in python

Tags:

python

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?

like image 754
Asif Avatar asked Nov 30 '22 23:11

Asif


2 Answers

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]
like image 158
mgilson Avatar answered Mar 07 '23 10:03

mgilson


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])
like image 21
Andy Hayden Avatar answered Mar 07 '23 11:03

Andy Hayden