python 计算小于某个数_python 列表寻找满足某个条件的开始索引和结束索引、区间范围...

在使用python列表的时候,我们经常需要找到满足某个条件的数的开始索引和结束索引,即满足某个条件的数的区间范围,本文以寻找绝对值大于等于0且小于等于3的数值区间为例,代码如下所示:

这是我在做项目写python代码的时候最常使用到的函数之一,分享给大家。

参考资料: https://stackoverflow.com/questions/48076780/find-starting-and-ending-indices-of-list-chunks-satisfying-given-condition

# 列表中找到符合要求的数的起始索引和结尾索引def first_and_last_index(li, lower_limit=0, upper_limit=3):    result = []    foundstart = False    foundend = False    startindex = 0    endindex = 0    for i in range(0, len(li)):        if abs(li[i]) >= lower_limit and abs(li[i]) <= upper_limit:            if not foundstart:                foundstart = True                startindex = i        else:            if foundstart:                foundend = True                endindex = i - 1        if foundend:            result.append((startindex, endindex))            foundstart = False            foundend = False            startindex = 0            endindex = 0    if foundstart:        result.append((startindex, len(li)-1))    return result

运行结果如下:

2592019166b35da71cdc9a4f53b57835.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值