查找数组中元素的 运行 - python

Find the run of elements in an array- python

我这里有一个列表:

a = [1, 1, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25,1,0.25,0.25].

列表a中,我要打印

1 : [0,1]

0.5 : [2,3]

0.25 : [4,5,6,7]

1 : [8,8]

0.25 : [9,10]

我试过的是这样的:

import numpy as np
a = [1, 1, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25,1,0.25,0.25]

b = np.array(a).reshape(1,len(a))

x = [1,0.5,0.25]

for v in x:

    c = b - v
    indices = []


##    for i in range(len(c[0])):
##        if c[0,i] == 0.:
##            indices.append(i)
##    print(v,indices)

    i = 0
    
    while i  < len(c[0]):
        if c[0,i] == 0.:
            indices.append(i)
        i = i + 1
        if len(indices) > 1 and indices[-1] != (indices[-2]+1): #len(indices) > 2 and 
            #i = i - 1
            indices = indices[:-1]
            print(i,v,indices)
            indices = []
            
        if len(indices) > 1 and i != (indices[-1]+1):
            print(i,v,indices)
            indices = []

但输出是:

1 [0, 1]

0.5 [2, 3]

0.25 [4, 5, 6, 7]

你能帮帮我吗?

您可以将其写成一个漂亮的生成器函数,用于跟踪当前 运行 的值和索引:

def find_runs(a):
    if not a:
        return
    curr_run = None
    for i, v in enumerate(a):
        if not curr_run:
            curr_run = (v, [i])
        elif v == curr_run[0]:
            curr_run[1].append(i)
        else:
            yield curr_run
            curr_run = (v, [i])
    yield curr_run


for val, indexes in find_runs([1, 1, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25, 1, 0.25, 0.25]):
    print(val, indexes)

输出为

1 [0, 1]
0.5 [2, 3]
0.25 [4, 5, 6, 7]
1 [8]
0.25 [9, 10]

此代码也有效: (在@AKX给出正确的解决方案后,我找到了自己的答案)

import numpy as np
from more_itertools import consecutive_groups
a = [1, 1, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25,1,0.25,0.25]

b = np.array(a).reshape(1,len(a))

x = [1,0.5,0.25]

for v in x:


    d = np.where(b[0] == v)

    for group in consecutive_groups(d[0].tolist()):
        print(v,list(group))