为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕娘9325324 2021-10-19 16:27:36
我试图找到一种有效的方法来搜索三个或更多连续的重复项,并将它们替换为 Python 列表中的一个。list_before = [1, 1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8]# expectedlist_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]这里似乎有什么问题?有没有更有效的方法?
查看完整描述

3 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

我很好的用例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]

有可能制作一个单行,itertools.chain但for循环几乎可以肯定更具可读性和类似的性能。


查看完整回答
反对 回复 2021-10-19
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

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


查看完整回答
反对 回复 2021-10-19
?
慕仙森

TA贡献1827条经验 获得超7个赞

正如克里斯在他的回答中指出的那样,单线是可能的,但它一点也不漂亮。


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在处理不可迭代对象时已经足够了。


查看完整回答
反对 回复 2021-10-19
  • 3 回答
  • 0 关注
  • 354 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信