Python 查找出现次数超过 3 次的重复项

我试图找到一种有效的方法来搜索三个或更多连续的重复项,并将它们替换为 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]

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


慕娘9325324
浏览 356回答 3
3回答

喵喔喔

我很好的用例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):...&nbsp; &nbsp; &nbsp;lst = list(group)...&nbsp; &nbsp; &nbsp;if len(lst) >= 3:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list_after.append(k)...&nbsp; &nbsp; &nbsp;else:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;list_after.extend(lst)>>> list_after[1, 2, 3, 4, 5, 6, 6, 7, 8]有可能制作一个单行,itertools.chain但for循环几乎可以肯定更具可读性和类似的性能。

肥皂起泡泡

>>>&nbsp;from&nbsp;itertools&nbsp;import&nbsp;groupby >>>&nbsp;nums&nbsp;=&nbsp;[1,&nbsp;1,&nbsp;1,&nbsp;2,&nbsp;3,&nbsp;4,&nbsp;5,&nbsp;5,&nbsp;5,&nbsp;6,&nbsp;6,&nbsp;7,&nbsp;7,&nbsp;7,&nbsp;8,&nbsp;8,&nbsp;8,&nbsp;8,&nbsp;8] >>>&nbsp;[k&nbsp;for&nbsp;k,&nbsp;g&nbsp;in&nbsp;groupby(nums)&nbsp;for&nbsp;i&nbsp;in&nbsp;range(1&nbsp;+&nbsp;(len(list(g))&nbsp;==&nbsp;2))]&nbsp;[1,&nbsp;2,&nbsp;3,&nbsp;4,&nbsp;5,&nbsp;6,&nbsp;6,&nbsp;7,&nbsp;8]

慕仙森

正如克里斯在他的回答中指出的那样,单线是可能的,但它一点也不漂亮。In [88]: list(chain.from_iterable([(x,) if len(y) >= 3 else y for x, y in [(k, tuple(g)) for k, g in groupby(list_before)]]))Out[88]: [1, 2, 3, 4, 5, 6, 6, 7, 8]我认为应该有更好的方法,但chain在处理不可迭代对象时已经足够了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python