Removing elements that have consecutive duplicates

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

提交回复
热议问题