删除具有连续重复项的元素 [英] Removing elements that have consecutive duplicates

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

问题描述

我对以下问题感到好奇:消除列表元素的连续重复项 ,以及应如何在Python中实现.

I was curios about the question: Eliminate consecutive duplicates of list elements, and how it should be implemented in Python.

我想到的是这个

list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0

while i < len(list)-1:
    if list[i] == list[i+1]:
        del list[i]
    else:
        i = i+1

输出:

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

我猜这还可以.

所以我很好奇,想知道是否可以删除具有重复项的元素并获得以下输出:

So I got curious, and wanted to see if I could delete the elements that had consecutive duplicates and get this output:

[2, 3, 5, 1, 2]

为此,我这样做了:

list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
i = 0
dupe = False

while i < len(list)-1:
    if list[i] == list[i+1]:
        del list[i]
        dupe = True
    elif dupe:
        del list[i]
        dupe = False
    else:
        i += 1

但是似乎有点笨拙而不是pythonic,您是否有任何更聪明/更优雅/更有效的方法来实现此目的?

But it seems sort of clumsy and not pythonic, do you have any smarter / more elegant / more efficient way to implement this?

推荐答案

>>> L = [1,1,1,1,1,1,2,3,4,4,5,1,2]
>>> from itertools import groupby
>>> [x[0] for x in groupby(L)]
[1, 2, 3, 4, 5, 1, 2]

如果愿意,可以使用map而不是列表理解

If you wish, you can use map instead of the list comprehension

>>> from operator import itemgetter
>>> map(itemgetter(0), groupby(L))
[1, 2, 3, 4, 5, 1, 2]

第二部分

>>> [x for x, y in groupby(L) if len(list(y)) < 2]
[2, 3, 5, 1, 2]

如果您不想创建临时列表只是为了获取长度,则可以在生成器表达式上使用sum

If you don't want to create the temporary list just to take the length, you can use sum over a generator expression

>>> [x for x, y in groupby(L) if sum(1 for i in y) < 2]
[2, 3, 5, 1, 2]

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

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