如何从列表中删除连续的重复项? [英] How do I remove consecutive duplicates from a list?

查看:106
本文介绍了如何从列表中删除连续的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从python这样的列表中删除连续的重复项?

How do I remove consecutive duplicates from a list like this in python?

lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]

拥有唯一的列表或集合并不能解决问题,因为前一个列表中有一些重复的值,例如1,...,1.

Having a unique list or set wouldn't solve the problem as there are some repeated values like 1,...,1 in the previous list.

我希望结果是这样的:

newlst = [1,2,4,1,3,5]

当我有这样的列表时,请您也考虑一下情况 [4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3] 我希望结果为[4,2,3,3] 而不是[4,2,3].

Would you also please consider the case when I have a list like this [4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3] and I want the result to be [4,2,3,3] rather than [4,2,3] .

推荐答案

itertools.groupby()是您的解决方案.

newlst = [k for k, g in itertools.groupby(lst)]


如果您希望通过项的值对组大小进行分组和限制,这意味着8 4将是[4,4],而9 3将是[3,3,3],这里有2个选项可以做到这一点:


If you wish to group and limit the group size by the item's value, meaning 8 4's will be [4,4], and 9 3's will be [3,3,3] here are 2 options that does it:

import itertools

def special_groupby(iterable):
    last_element = 0
    count = 0
    state = False
    def key_func(x):
        nonlocal last_element
        nonlocal count
        nonlocal state
        if last_element != x or x >= count:
            last_element = x
            count = 1
            state = not state
        else:
            count += 1
        return state
    return [next(g) for k, g in itertools.groupby(iterable, key=key_func)]

special_groupby(lst)

OR

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

newlst = list(itertools.chain.from_iterable(next(zip(*grouper(g, k))) for k, g in itertools.groupby(lst)))

选择任何您认为合适的方式.两种方法都适用于数字> 0.

Choose whichever you deem appropriate. Both methods are for numbers > 0.

这篇关于如何从列表中删除连续的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆