Check if in python multiple variables are greater than zero

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 a shorthand implementation for a given code structure.? Is there a better / elegant / convenient way to do this?

+4
source share
4 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 for the python ternary operator, it will look like this:

 v1, v2, v3, v4 = [max(x, 0) for x in (A, B, C, D)] 

However, if you plan to handle all of these variables in the same way, you might want to consider placing them in a list / tuple first.

 values = [200, -140, 400, -260] values = [max(x, 0) for x in values] 
+13
source

This can be easily solved using max() built-in and unzipping

+4
source

Functional check with min() and max() .

 v1 = max(0, A) 
+2
source

As an alternative to mgilson's excellent response, you can subclass int into a custom class to achieve this

 >>> class V(int): ... def __new__(cls,val,**kwargs): ... return super(V,cls).__new__(cls,max(val,0)) 

Then use it directly:

 >>> A=V(200) 200 >>> B=V(-140) 0 >>> [V(i) for i in [200, -140, 400, -260]] [200, 0, 400, 0] >>> A,B,C,D = [V(i) for i in [200, -140, 400, -260]] 

The only advantage that can be done this way is that you can override __sub__ and __add__ __mul__ , and then you will always be greater than V if you have a=V(50)-100

Example:

 >>> class V(int): ... def __new__(cls,val,**kwargs): ... return super(V,cls).__new__(cls,max(val,0)) ... def __sub__(self,other): ... if int.__sub__(self,other)<0: ... return 0 ... else: ... return int.__sub__(self,other) >>> a=V(50) >>> b=V(100) >>> ab #ordinarily 50-100 would be -50, no? 0 
0
source

Source: https://habr.com/ru/post/1435950/


All Articles