在Python中的列表中查找大于0的第一个和最后一个值

发布于 2025-01-29 01:00:26 字数 172 浏览 2 评论 0原文

它是基于太阳能测量系统的列表,因此在一天的头几个小时里为0,在一天的最后几个小时中为0,因此我有兴趣获得最小值和最大值大于0;示例:

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

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]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

橘味果▽酱 2025-02-05 01:00:26

您可以使用列表理解删除零,然后使用minmax函数。

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)

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)
旧故 2025-02-05 01:00:26

我鼓励您自己尝试,您通过编程学习编程。这绝对看起来像编程练习。

但是在这里,对于初学者来说,另一个更简单的解决方案。

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

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
离笑几人歌 2025-02-05 01:00:26

使用发电机理解来过滤值

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

Use a generator comprehension to filter the values, for ex

max(v for v in total_solar if v > 0)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文