Removing elements that have consecutive duplicates

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

    Here is a solution without dependence on outside packages:

    list = [1,1,1,1,1,1,2,3,4,4,5,1,2] 
    L = list + [999]  # 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
    

    Then I noted that Ulf Aslak's similar solution is cleaner :)

提交回复
热议问题