找到满足给定条件的列表块的开始和结束索引

Find starting and ending indices of list chunks satisfying given condition

我正在尝试查找列表中正数块的开始和停止索引。

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] 

对于给定的示例输入,所需的输出是:

[(0, 2), (7, 9), (14, 17), (21, 25), (29, 30)]

使用一些标志来跟踪您在检查过程中的位置并使用一些变量来保存历史信息如何?

这不是超级优雅的代码,但我认为它相当容易理解,并且对于您提供的用例来说相当稳健。

我的代码

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5] 
foundstart = False
foundend = False
startindex = 0
endindex = 0
for i in range(0, len(cross)):
    if cross[i] != 0:
        if not foundstart:
            foundstart = True
            startindex = i
    else:
        if foundstart:
            foundend = True
            endindex = i - 1

    if foundend:
        print(startindex, endindex)
        foundstart = False
        foundend = False
        startindex = 0
        endindex = 0

if foundstart:
    print(startindex, len(cross)-1)

输出

0 2
7 9
14 17
21 25
29 30

更简单的方法是 enumerate the values of the given list, and then group the index-value pairs by given condition with the help of itertools.groupby。从那里获取索引是微不足道的:

from itertools import groupby

cross = [7,5,8,0,0,0,0,2,5,8,0,0,0,0,8,7,9,3,0,0,0,3,2,1,4,5,0,0,0,7,5]
indexed_cross = enumerate(cross)  # will yield pairs (0, 7), (1, 5), (2, 8)...
key = lambda x: x[1] > 0  # will give True for pairs with positive second items
indices = []
for key, group in groupby(indexed_cross, key=key):
    if key:  # True for positive-values groups
        chunk = list(group)
        indices.append((chunk[0][0], chunk[-1][0]))  # extracting the indices
print(indices)
# [(0, 2), (7, 9), (14, 17), (21, 25), (29, 30)]

或者,NumPy 可用于更大的数组:

import bumpy as np

cross = np.array(cross)
padded_values = np.r_[-cross[0], cross, -cross[-1]]  # accounting for the first and the last indices
indices = np.where(np.diff(padded_values > 0) != False)[0]
indices = indices.reshape(-1, 2)
indices[:, 1] -= 1
print(indices)
# [[ 0  2]
#  [ 7  9]
#  [14 17]
#  [21 25]
#  [29 30]]