wordpress推荐商品主题,新站seo竞价,网站提供入口,部门网站建设情况总结在使用python列表的时候#xff0c;我们经常需要找到满足某个条件的数的开始索引和结束索引#xff0c;即满足某个条件的数的区间范围#xff0c;本文以寻找绝对值大于等于0且小于等于3的数值区间为例#xff0c;代码如下所示#xff1a;这是我在做项目写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_limit0, upper_limit3): 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运行结果如下