Python - 获取列表的索引,所有进一步的条目都满足条件

Python - get index of list from which on all further entries satisfy condition

假设我有一个列表

l = [12,13,14,10,13,14]

我想找到所有项目都大于 10 的索引(在这种情况下,它是对应于 13 的索引 4 作为第一次出现这个 属性).

也许基于 ,如何使用 Python 做到最好?

我的想法:为此创建一个布尔列表 [a>10 for a in l] (由 TrueFalse 作为序列组成),或者 l>10 使用 numpy?

以某种方式产生一个数组

给你:

[l.index(item) for item in l if not item>10][-1]+1

您可以向后遍历列表并捕获第一个条件失败的索引。这可以防止出现多个值失败的问题...

In [51]: l                                                                                  
Out[51]: [12, 13, 14, 10, 13, 14]

In [52]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
Out[52]: 4

In [53]: l = [12, 13, 10, 20, 10, 15]                                                       

In [54]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         
Out[54]: 5

In [55]: l = [23, 55]                                                                       

In [56]: next((len(l) - idx for idx, val in enumerate(l[::-1]) if val <= 10), None)         

In [57]: 

 
l = [12,13,14,10,13,14]
i = len(l)
for i in reversed(l):
    condition = v > 10
    if not condition:
        break
    i -= 1
print(i)
# Output : 4

注意列表最后一个元素不满足条件的情况。 i 值将等于 len(l) wich 不是列表的有效索引。您可以选择如何处理这种特殊情况。

您可以从数组的末尾开始:

def findStartOfMoreThan(l,limit):
    for i in range(len(l)-1, -1, -1):
        if l[i]<=limit :
            return i+1
    return (-1)
    
assert(findStartOfMoreThan([12,13,14,10,13,14],10) == 4)
assert(findStartOfMoreThan([12,13,14,10,13,14,15],10)==4)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],10)==5)
assert(findStartOfMoreThan([0,12,13,14,10,13,14,15],13)==6)

最简单的解决方案是使用

否定条件以获得具有 element <=10 的最后一个索引
l = np.array([12,13,14,10,13,14])
first_index = np.where(l<=10)[0][-1]+1 # yields the first index that satisfies the condition

可以先检查 len(np.where(...)) 以验证条件至少被违反一次,否则 return 第一个索引为 0。