python - 如何从列表中删除每 12 个零

标签 python arrays list numpy

我有一个列表如下:

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

我想从列表中删除连续重复 12 次的零,以获得所需的输出

a = [1, 1, 0, 0, 1, 1]

我尝试使用索引,但很快意识到这也会删除不重复 12 次的零...

index = [0]
new_a = np.delete(a, index)
print(new_a)

最佳答案

代码

每一行都很好理解。

buffer = []
result = []
for n in num:
    if n == 0:
        buffer.append(n)
    if n == 1:
        if len(buffer) < 12:
            result.extend(buffer)
        result.append(n)
        buffer = []
if len(buffer) < 12:
    result.extend(buffer)
[1, 1, 0, 0, 1, 1]

技巧答案

  • 使用正则表达式
  • 您可以在 python.re 了解它
import re
line = "".join(str(n) for n in num)
ans = re.sub(r"0{12,}", "", t)
res = [int(n) for n in ans]
[1, 1, 0, 0, 1, 1]

关于python - 如何从列表中删除每 12 个零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72181628/

相关文章:

python - loadtxt 函数的隐藏错误

arrays - VBA:数组中的名称表

list - Java : sort list of lists

python - 读取文件,输出UTF-8/Unicode

python - 禁用或锁定文本编辑 PyQT

python - Python 中的希尔伯特变换?

python - 使用 MapReduce 是否可以保证具有相同键的所有值都将进入相同的 reducer?

jquery - 如何将Json数组显示到tinymce

performance - 在 Haskell 的列表列表中有效地找到多个最大值

c# - 从文件加载 TextAsset 且无法比较