Removing elements that have consecutive duplicates

后端 未结 9 1255
眼角桃花
眼角桃花 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: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'
    

提交回复
热议问题