Skip to main content
 首页 » 编程设计

python之检查列表中的值是否超过阈值一定次数并返回第一次超过的索引

2025年05月04日26mfrbuaa

我正在寻找一种干净的 pythonic 方法来检查列表的内容是否大于给定数字(第一个阈值)一定次数(第二个阈值)。如果两个语句都为真,我想返回第一个超过给定阈值的值的索引。

示例:

# Set first and second threshold 
thr1 = 4 
thr2 = 5 
 
# Example 1: Both thresholds exceeded, looking for index (3) 
list1 = [1, 1, 1, 5, 1, 6, 7, 3, 6, 8] 
 
# Example 2: Only threshold 1 is exceeded, no index return needed 
list2 = [1, 1, 6, 1, 1, 1, 2, 1, 1, 1] 

请您参考如下方法:

我不知道滥用 bool 值是整数这一事实是否被认为是 pythonic,但我喜欢这样做

def check(l, thr1, thr2): 
    c = [n > thr1 for n in l] 
    if sum(c) >= thr2: 
        return c.index(1)