亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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條經驗 獲得超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在處理不可迭代對象時已經足夠了。


查看完整回答
反對 回復 2021-10-19
  • 3 回答
  • 0 關注
  • 425 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號