在列表

时间:2018-01-03 11:47:57

标签: python arrays list if-statement conditional

我正在尝试找到数字的开始和停止索引>列表中的0

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后跟索引值= 0.

期望的输出:

(0 2),(7 9), (14 17)..

实际输出:

(2 3), (7 8)..

我的代码

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)   
for i in range(0,len(cross)): 
    if cross[i]==0:
        while(cross[i-1]>0):
            i+=1
            print(i-1,i)  

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

一种更简单的方法是enumerate给定列表的值,然后在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]]