gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:51:49 25 4
gpt4 key购买 nike

例如,我在 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]
...

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

最佳答案

你可以使用 itertools.groupby ,它将识别列表中的连续组:

from itertools import groupby

lst = [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 = 0
result = []
for k, l in groups:
if not k and l >= 5:
result.append([cursor, cursor + l - 1])
cursor += l

print(result)

输出

[[17, 21], [30, 35]]

关于python - 查找连续的重复项并列出它们在 python 中出现位置的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54596872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com