如何更清晰实现查找列表中最后一个≥阈值元素的索引?
优化方案:查找列表中最后一个≥阈值的元素索引
方案1:反向遍历+枚举
从列表末尾开始遍历,找到第一个符合条件的元素就返回索引,逻辑直观,无需遍历整个列表:
a = [10, 8, 7, 5, 4, 4, 4, 2, 1, 1, 1] threshold = 4 for idx, num in reversed(list(enumerate(a))): if num >= threshold: print(idx) # 输出6 break
方案2:列表推导式+max函数
先筛选出所有符合条件的元素索引,再取最大值,语义清晰易懂:
a = [10, 8, 7, 5, 4, 4, 4, 2, 1, 1, 1] threshold = 4 valid_indices = [i for i, num in enumerate(a) if num >= threshold] last_idx = max(valid_indices) if valid_indices else -1 # 无符合条件元素时返回-1 print(last_idx) # 输出6
方案3:numpy向量化操作(适合数值型列表)
如果处理大规模数值数据,numpy的向量化操作效率更高:
import numpy as np a = np.array([10, 8, 7, 5, 4, 4, 4, 2, 1, 1, 1]) threshold = 4 mask = a >= threshold last_idx = np.where(mask)[0][-1] if any(mask) else -1 print(last_idx) # 输出6
内容的提问来源于stack exchange,提问作者hslin
相关产品推荐
相关产品推荐

