python - 如何在 bool 值中返回最长连续出现的 "True",并将其他True替换为False?

标签 python numpy more-itertools

我正在尝试返回一个 bool 值,它只给出原始 bool 值中最长的“True”出现并将较短的“True” block 替换为“False”。示例 a=[True, True, False, True , True, True, False],我想返回 [False, False, False, True, True, True, False]。

我尝试了 more_itertools,它似乎有一些有趣的功能,但不确定如何准确地实现我的目的。

a=[True, True, False, True , True, True, False]

pred = lambda x: x in {True}

p=list(mit.run_length.encode(a))

>>>
Results in: (True,2),(False,1),(True,3),(False,1)

所以我想最终自动得到的是(False,3),(True,3),(False,1)。有什么建议么? 谢谢你的帮助

最佳答案

以下解决方案在使用 more_itertools.run_length 后应该有效.

本质上,逻辑是找到 True 的最长子序列的长度,以及该索引在 result 列表中的位置
然后计算最长子序列前后的元素总数,然后相应地构造结果元组列表。

import more_itertools as mit

a=[True, True, False, True , True, True, False]

result = list(mit.run_length.encode(a))

#Find the length of longest subsequence of True, and the location if that index in result
max_true_count = -1
max_true_idx  = -1
for idx, (val, count) in enumerate(result):
    if val and max_true_count < count:
        max_true_count = count
        max_true_idx = idx

#Find total elements before and after the longest subsequence tuple
elems_before_idx = sum((idx[1] for idx in result[:max_true_idx]))
elems_after_idx = sum((idx[1] for idx in result[max_true_idx+1:]))

#Create the output list using the information
output = [(False, elems_before_idx), (True, max_true_count), (False, elems_after_idx)]
print(output)

输出将是

[(False, 3), (True, 3), (False, 1)]

关于python - 如何在 bool 值中返回最长连续出现的 "True",并将其他True替换为False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301970/

相关文章:

python - 在用户注册时发送密码,django-allauth

python - 如何获取Conv2D层Tensorflow中的步幅值?

opencv - 为什么 pyplot.imshow() 改变数组中的颜色 channel

python - 当存在重复值时将 numpy.array 转换为元素顺序

python - 纯Python或itertools按每个日期之间的天数差异对日期列表进行分组

python - GROUP BY python 后总大小的百分比

python - Numpy *.npz 内部文件结构

python - 内存映射文件如何处理大于内存的文件?

python - 运行 pytest 时 more-itertools 中的语法无效