【问题标题】:Find the run of elements in an array- python查找数组中元素的运行-python
【发布时间】:2021-05-07 08:35:14
【问题描述】:

我这里有一个清单:

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]

你能帮帮我吗?

【问题讨论】:

    标签: python iteration counter


    【解决方案1】:

    你可以把它写成一个漂亮的生成器函数来跟踪当前运行的值和索引:

    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]
    

    【讨论】:

      【解决方案2】:

      此代码也有效: (@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))
      

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 2015-01-31
        • 2022-01-09
        • 2017-04-11
        • 1970-01-01
        • 2012-09-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多