猿问

删除具有连续重复项的元素

我对以下问题感到好奇:消除列表元素的连续重复,以及如何在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]

我猜没关系。


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


[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,您是否有任何更聪明/更优雅/更有效的方法来实现这一点?


qq_遁去的一_1
浏览 392回答 3
3回答

catspeake

这是不依赖外部程序包的解决方案:list = [1,1,1,1,1,1,2,3,4,4,5,1,2]&nbsp;L = list + [999]&nbsp; # append a unique dummy element to properly handle -1 index[l for i, l in enumerate(L) if l != L[i - 1]][:-1] # drop the dummy element然后我注意到,Ulf Aslak的类似解决方案更干净:)
随时随地看视频慕课网APP

相关分类

Python
我要回答