python - 如果为真 : turn following values to True in list of booleans until nth position after True is reached

标签 python list iterator boolean iteration

我有一个 boolean 值列表

l = [False, False, False, True, False, False, False]

我想变成

l_new = [False, False, False, True, True, True, False]

这意味着,每当我的列表中有 True 时,我想将以下两个(例如)值切换为 true。 我的解决办法是

def lagged_effect(l, lag):
    l_new = []
    L_iter = iter(l)
    for elem in L_iter:
        if elem == True:
            l_new.extend([True]*lag)
            if lag == 1:
                next(L_iter)
            if lag == 2:
                next(L_iter)
                next(L_iter)
            if lag == 3:
                next(L_iter)
                next(L_iter)
                next(L_iter)
            if lag == 4:
                next(L_iter)
                next(L_iter)
                next(L_iter)
                next(L_iter)
            if lag > 4:
                print("not defined")
        if elem == False:
            l_new.append(False)
    return l_new
    print(l_new)
lagged_effect(l, lag=2)

由于我想更频繁地实现这一点,我想知道是否有更紧凑、更高效的解决方案。尤其是下一个实现让我很恼火。

最佳答案

使用列表移位和压缩以及 boolean 值或

l = [False, False, False, True, False, False, False]

out = [x or y or z for x, y, z in zip(l, [False] + l, [False]*2 + l)]
print(out)
[False, False, False, True, True, True, False]

任何滞后的选项

lag = 4
l = [False, False, False, True, False, False, False, False, False, True, False, False, False, False, True]
out = [any(z) for z in zip(*[[False] * n + l for n in range(lag + 1)])]
print(out)
[False, False, False, True, True, True, True, True, False, True, True, True, True, True, True]

关于python - 如果为真 : turn following values to True in list of booleans until nth position after True is reached,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73714097/

相关文章:

python - 类型错误:一元的错误操作数类型-: 'str'

python - 用另一个列表对元组列表进行排序

c++ - 在构造函数中调用列表上的迭代器会更改其最终值吗?

c++ - STL vector 通过指针删除

python - bottle_mysql 编码失败

python - 在 Python 3 中可以结合参数描述和类型提示吗?

c++ - C/C++ 链表永远不为空

Java流程控制问题

java - 为什么我们需要在 Java 中的 ArrayList 上使用迭代器?

python - Django 序列化器字段值基于同一序列化器中的其他字段