Removing elements that have consecutive duplicates

后端 未结 9 1239
眼角桃花
眼角桃花 2020-11-22 10:02

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

What I came up with is this:

相关标签:
9条回答
  • 2020-11-22 10:41

    A "lazy" approach would be to use itertools.groupby.

    import itertools
    
    list1 = [1, 2, 3, 3, 4, 3, 5, 5]
    list1 = [g for g, _ in itertools.groupby(list1)]
    print(list1)
    

    outputs

    [1, 2, 3, 4, 3, 5]
    
    0 讨论(0)
  • 2020-11-22 10:42

    Another possible one-liner, using functools.reduce (excluding the import) - with the downside that string and list require slightly different implementations:

    >>> from functools import reduce
    
    >>> reduce(lambda a, b: a if a[-1:] == [b] else a + [b], [1,1,2,3,4,4,5,1,2], [])
    [1, 2, 3, 4, 5, 1, 2]
    
    >>> reduce(lambda a, b: a if a[-1:] == b else a+b, 'aa  bbb cc')
    'a b c'
    
    0 讨论(0)
  • 2020-11-22 10:46

    If you use Python 3.8+, you can use assignment expression :=:

    list1 = [1, 2, 3, 3, 4, 3, 5, 5]
    
    prev = object()
    list1 = [prev:=v for v in list1 if prev!=v]
    
    print(list1)
    

    Prints:

    [1, 2, 3, 4, 3, 5]
    
    0 讨论(0)
提交回复
热议问题