查找满足给定条件的列表块的起始和结束索引。

问题描述 投票:-4回答:2

我试图找到一个列表中正数块的起始和终止指数。

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)]
python list indices
2个回答
1
投票

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

这不是一个超级优雅的代码,但我认为它是相当简单易懂的,而且对于你给出的用例来说也是相当稳健的。

我的代码

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

0
投票

一个更简单的方法是 列举 的值,然后在给定条件下,借助于 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]]
© www.soinside.com 2019 - 2024. All rights reserved.