Python查找重复次数超过3次

J. *_*Doe 6 python list

我试图找到一种有效的方法来搜索三个或更多连续的重复项,并在Python列表中只替换它们一个.

list_before = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8]

# expected
list_after = [1, 2, 3, 4, 5, 6, 6, 7, 8]

def replace(list_to_replace):
    for idx, val in enumerate(list_to_replace):
        if idx + 3 < len(list_to_replace):
            if val == list_to_replace[idx+1] == list_to_replace[idx+2]:
                del list_to_replace[idx+1]
                del list_to_replace[idx+2]
    return list_to_replace

>>> replace(list_before)
[1, 1, 3, 4, 5, 5, 6, 7, 7, 8, 8, 8]
Run Code Online (Sandbox Code Playgroud)

这里似乎有什么问题?有更有效的方法吗?

Chr*_*nds 10

我很好的用例itertools.groupby:

>>> from itertools import groupby
>>> list_before = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8]
>>> list_after = []
>>> for k, group in groupby(list_before):
...     lst = list(group)
...     if len(lst) >= 3:
...         list_after.append(k)
...     else:
...         list_after.extend(lst)
>>> list_after
[1, 2, 3, 4, 5, 6, 6, 7, 8]
Run Code Online (Sandbox Code Playgroud)

有可能制作一个单行,itertools.chainfor循环几乎肯定更具可读性和性能相似.

  • 我更倾向于使用你的,而不是去单行,这不仅要处理消耗生成器/迭代器的怪癖,它还必须处理`链`对非迭代的明显仇恨,哈哈. (2认同)