gpt4 book ai didi

python - 列表中满足条件的元素序列

转载 作者:太空狗 更新时间:2023-10-29 20:26:08 24 4
gpt4 key购买 nike

假设我有一个这种类型的列表:

#    0   1  2  3   4  5  6  7  8  9   10  11 -- list index
li=[-1, -1, 2, 2, -1, 1, 1, 1, 1, 1, -1, -1 ]

我想找到每个索引,其值对于以下索引的 n 是相同的。

我可以(费力地)这样做:

def sub_seq(li,n):
ans={}
for x in set(li):
ans[x]=[i for i,e in enumerate(li[:-n+1]) if all(x==y for y in li[i:i+n])]

ans={k:v for k,v in ans.items() if v}

return ans

li=[-1, -1, 2, 2, -1, 1, 1, 1, 1, 1, -1, -1]
for i in (5,4,3,2):
print i, sub_seq(li,i)

打印:

5 {1: [5]}
4 {1: [5, 6]}
3 {1: [5, 6, 7]}
2 {1: [5, 6, 7, 8], 2: [2], -1: [0, 10]}

有更好的方法吗?

最佳答案

如果您先将数据转换为方便的形式,那么分析数据通常会更容易。在这种情况下,一个 run-length-encoding将是一个很好的起点:

from itertools import groupby, accumulate
from collections import defaultdict

def sub_seq(li, n):
d = defaultdict(list)
rle = [(k, len(list(g))) for k, g in groupby(li)]
endpoints = accumulate(size for k, size in rle)
for end_index, (value, count) in zip(endpoints, rle):
for index in range(end_index - count, end_index - n + 1):
d[value].append(index)
return dict(d)

关于python - 列表中满足条件的元素序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502788/

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