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

标签 python duplicates

<分区>

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

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

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

我希望结果是这样的:

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]

最佳答案

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

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

如果您希望按项目的值分组并限制组的大小,这意味着 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)

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 的数字。

关于python - 如何从列表中删除连续的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39237350/

相关文章:

html - CSS 两个可点击元素显示不同的内容

java - 从java中的Arraylist中的列表中删除重复项

删除重复项,保留具有最大绝对值的条目

python - 如何在新电子邮件中发送现有消息而不丢失格式

python - 切割轴的边界

python - Pytest cov 不读取 pyproject.toml

python - 如何使用 python pandas 对分割文本进行分组并计算其数量?

python - 拟合曲线: which model to describe distribution in weighted knowledge graphs

mysql - 删除 MySQL 中的重复行

C++ - 从结构的排序 vector 中删除重复项