提问者:小点点

自定义扫描连续值的列表


我的名单如下:

A = [3 1 2 3 0 4 3 1 2 3 1 0 0 0 1]

给定初始索引(例如,id=5),我希望找到列表中最后一项(ld)的索引,以便idld之间的所有值都大于零(包括零)。考虑这个例子:

如果id=5A[5]=4),则ld=10ld=1)。

A = [3 1 2 3 0 4 3 1 2 3 1 0 0 0 1]

最有效的方法是什么?


共2个答案

匿名用户

您可以有一个包含Trueiff条件(元素)的伴随列表

把它们都放在一起:

p = [x > 0 for x in A] + [False]

# then
id_ = 5  # don't shadow id
p.index(False, id_) - 1
# gives 10

匿名用户

下面是一个避免在列表上使用显式索引的解决方案

import itertools as it
from typing import Iterable


def f(iterable: Iterable, start: int) -> int:
    try:
        pos, _ = next(
            it.dropwhile(
                lambda el: el[1]>0,
                enumerate(
                    it.islice(iterable, start, None),
                    start=start
                )
            )
        )
    except StopIteration:
        pos = len(iterable)
    return pos - 1


a = [3, 1, 2, 3, 0, 4, 3, 1, 2, 3, 1, 0, 0, 0, 1]
print(f(a, 5))

b = [3, 1, 2, 3, 0, 4, 3, 1, 2, 3, 1, 3, 3, 3, 1]
print(f(b, 5))

从而产生

10
14