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

标签 python python-3.x list

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

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

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

例如上面的列表,第一个 1 到下一个 1 的距离为 3。第二个 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]。

最佳答案

存储您第一次引用的第一个 1 的索引,然后当您到达 last 1 时,您只需添加索引第一个加上最后一个 1 之后的 0 元素的数量以获得该距离(因此 len(inputlist) - lastindex + firstindex)。

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

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]

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

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

和 1 1 值给你 1 个距离:

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

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

关于python - 用于查找索引之间距离的列表换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407849/

相关文章:

python - 列表理解的多个非连接条件

python - Print 打印一些额外的标志

python - 如何根据状态码重试异步 aiohttp 请求

python - 如何绘制 Shapely 点列表

python - 如何设计 django 中已经存在的表单样式

python - 如何使 cx_Freeze python exe 无窗口

python - Docker 镜像未使用指定的 Python 版本运行

python - 在 Bokeh 中悬停多行字形时如何显示单个值?

java - jpa ClassCastException Long 无法转换为 List

css - Sencha Touch 自定义列表行