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

Elm*_*ahy 5 python duplicates

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

lst = [1,2,2,4,4,4,4,1,3,3,3,5,5,5,5,5]
Run Code Online (Sandbox Code Playgroud)

拥有唯一的列表或集合无法解决问题,因为在上一个列表中存在一些重复值,如1,...,1.

我希望结果是这样的:

newlst = [1,2,4,1,3,5]
Run Code Online (Sandbox Code Playgroud)

如果我有这样的列表,我还要考虑这个案例 [4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3] ,我希望结果[4,2,3,3] 不是[4,2,3].

Bha*_*rel 11

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

newlst = [k for k, g in itertools.groupby(lst)]
Run Code Online (Sandbox Code Playgroud)

如果你想按照项目的值对组大小进行分组和限制,意味着8 4将是[4,4],9 3将是[3,3,3],这里有2个选项:

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)
Run Code Online (Sandbox Code Playgroud)

要么

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)))
Run Code Online (Sandbox Code Playgroud)

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