代码之家  ›  专栏  ›  技术社区  ›  Keegan Husom

用于查找索引之间距离的列表换行

  •  3
  • Keegan Husom  · 技术社区  · 8 年前

    我有一个随机生成的列表,看起来像:

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

    我需要找出1之间的所有距离,包括环绕的距离。

    例如,上面的列表中,第一个1与下一个1之间的距离为3。第二个1与以下1之间的距离为1,依此类推。

    如何使用环绕到第一个1来查找列表中最后一个1的距离?

    def calc_dist(loc_c):
       first = []
       #lst2 = []
       count = 0
       for i in range(len(loc_c)):
           if loc_c[i] == 0:
               count += 1
               #lst2.append(0)
           elif loc_c[i] == 1:
               first.append(i)
               count += 1
               loc_c[i] = count
               #lst2.append(loc_c[i])
               #if loc_c[i] + count > len(loc_c):
                   # x = loc_c[first[0] + 11 % len(loc_c)]
                   # loc_c[i] = x
               count = 0
    
       return loc_c
    

    我的预期结果应该是[3,1,2,4]。

    3 回复  |  直到 7 年前
        1
  •  2
  •   Bram Vanroy    8 年前

    干净整洁:

    def calc_dist(l):
        idx = [i for i, v in enumerate(l) if v]
        if not idx: return []
        idx.append(len(l)+idx[0])
        return [idx[i]-idx[i-1] for i in range(1,len(idx))]
    
    print(calc_dist([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
    # [3, 1, 2, 4]
    print(calc_dist([0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
    # [3, 1, 2, 7]
    print(calc_dist([0, 0, 0, 0])
    # []
    
        2
  •  5
  •   Martijn Pieters    8 年前

    存储第一个的索引 1 你先参考,然后当你到达 最后的 您只需要添加第一个的索引加上 0 最后一个元素之后的元素 为了达到这个距离(所以 len(inputlist) - lastindex + firstindex )

    其他距离是前面的距离之差 值和当前索引。

    from typing import Any, Generator, Iterable
    
    def distances(it: Iterable[Any]) -> Generator[int, None, None]:
        """Produce distances between true values in an iterable.
    
        If the iterable is not endless, the final distance is that of the last
        true value to the first as if the sequence of values looped round.
    
        """
        first = prev = None
        length = 0
        for i, v in enumerate(it):
            length += 1
            if v:
                if first is None:
                    first = i
                else:
                    yield i - prev
                prev = i
        if first is not None:
            yield length - prev + first
    

    上面的生成器在序列上循环时计算距离 seq 一个接一个地给他们:

    >>> for distance in distances([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]):
    ...     print(distance)
    ...
    3
    1
    2
    4
    

    打电话就行了 list() 在发电机上,如果必须有列表输出:

    >>> list(distances([1, 0, 0, 1, 1, 0, 1, 0, 0, 0]))
    [3, 1, 2, 4]
    

    如果没有 值,这导致零距离产生:

    >>> list(distances([0, 0, 0]))
    []
    

    和1 值为1距离:

    >>> list(distances([1, 0, 0]))
    [3]
    

    我已经使解决方案具有足够的通用性,能够处理 任何不可更改的 ,即使是无限的;这意味着您也可以使用另一个生成器来为它供电。如果给定一个至少产生 一些 非零值,它只会持续产生距离。

        3
  •  1
  •   Mathieu    8 年前

    您可以使用numpy:

    import numpy as np
    
    L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0])
    id = np.where(test == 1)[0]
    
    # id = array([0, 3, 4, 6], dtype=int64)
    
    res = [id[i]-id[i-1] for i in range(1, len(id))]
    # [3, 1, 2]
    
    # Last distance missing:
    res.append(len(L)- id[-1])
    
    res = [3, 1, 2, 4]
    

    请注意,您请求的信息包含在上面,但输出格式可能有误。你不是很具体…

    编辑:生成随机列表后如何将列表转换为数组

    L = [1, 0, 0, 1, 1, 0, 1, 0, 0, 0]
    np.asarray(L)
    

    edit2:如何检查列表中是否没有1:

    import numpy as np
    
    L = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 0])
    id = np.where(test == 1)[0]
    
    if len(id) == 0:
        res = []
    else:
        res = [id[i]-id[i-1] for i in range(1, len(id))]
        res.append(len(L)- id[-1])
    

    或:

    try:
        res = [id[i]-id[i-1] for i in range(1, len(id))]
        res.append(len(L)- id[-1])
    except:
        res = []