Home > Software engineering >  Find first and last value greater than 0 in a list in python
Find first and last value greater than 0 in a list in python

Time:05-15

It is a list based on a solar measurement system so in the first hours of the day it will be 0 and in the last hours of the day it will be 0, so I am interested in obtaining the minimum and maximum value greater than 0; example:

total_solar=[0,0,0,0,0,100,200,200,300,200,200,120,0,0,0,0,0]

CodePudding user response:

You can remove the zeros with list comprehension then use the min and max functions.

total_solar=[0,0,0,0,0,100,200,200,300,200,200,120,0,0,0,0,0]
non_zero = [i for i in total_solar if i]
min_val = min(non_zero)
max_val = max(non_zero)

CodePudding user response:

I encourage you to try by yourself, you learn programming by programming. This definitely looks like programming exercise.

But here another solution simpler for beginner.

total_solar=[0,0,0,0,0,100,200,200,300,200,200,120,0,0,0,0,0]
min_non_zero = -1 # init value
max_non_zero = -1 # init value

for element in total_solar:
    if element != 0: # in python if 0 give False so you could use use if element
        if min_non_zero < 0  or element < min_non_zero:
            min_non_zero = element
        if max_non_zero < 0 or element > max_non_zero:
            max_non_zero = element

print(min_non_zero, max_non_zero)

100 300

CodePudding user response:

Use a generator comprehension to filter the values, for ex

max(v for v in total_solar if v > 0)
  • Related