'Find first and last value greater than 0 in a list in python
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]
Solution 1:[1]
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)
Solution 2:[2]
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
Solution 3:[3]
Use a generator comprehension to filter the values, for ex
max(v for v in total_solar if v > 0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alexpdev |
| Solution 2 | RomainL. |
| Solution 3 | cards |
