查找连续的重复项并列出它们在 python 中出现的位置的索引

例如,我在 python 中有一个列表:


mylist = [1,1,1,1,1,1,1,1,1,1,1,

        0,0,1,1,1,1,0,0,0,0,0,

        1,1,1,1,1,1,1,1,0,0,0,0,0,0]

我的目标是找到一行中有五个或更多零的位置,然后列出发生这种情况的位置的索引,例如,输出将是:


[17,21][30,35]

这是我在此处提出的其他问题中尝试/看到的内容:


def zero_runs(a):

    # Create an array that is 1 where a is 0, and pad each end with an extra 0.

    iszero = np.concatenate(([0], np.equal(a, 0).view(np.int8), [0]))

    absdiff = np.abs(np.diff(iszero))

    # Runs start and end where absdiff is 1.

    ranges = np.where(absdiff == 1)[0].reshape(-1, 2)

    return ranges


    runs = zero_runs(list)

这给出了输出:


[0,10]

[11,12]

...

这基本上只是列出所有重复项的索引,我将如何将这些数据分成我需要的数据


HUX布斯
浏览 361回答 3
3回答

www说

您可以使用itertools.groupby,它将识别列表中的连续组:from itertools import groupbylst = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]groups = [(k, sum(1 for _ in g)) for k, g in groupby(lst)]cursor = 0result = []for k, l in groups:    if not k and l >= 5:        result.append([cursor, cursor + l - 1])    cursor += lprint(result)输出[[17, 21], [30, 35]]

慕盖茨4494581

使用itertools.groupbyand 的另一种方式enumerate。首先找到零点和索引:from operator import itemgetterfrom itertools import groupbyzerosList = [    list(map(itemgetter(0), g))     for i, g in groupby(enumerate(mylist), key=itemgetter(1))     if not i]print(zerosList)#[[11, 12], [17, 18, 19, 20, 21], [30, 31, 32, 33, 34, 35]]现在只需过滤zerosList:runs = [[x[0], x[-1]] for x in zerosList if len(x) >= 5]print(runs)#[[17, 21], [30, 35]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python