Removing elements that have consecutive duplicates

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

    To Eliminate consecutive duplicates of list elements; as an alternative, you may use itertools.zip_longest() with list comprehension as:

    >>> from itertools import zip_longest
    
    >>> my_list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
    >>> [i for i, j in zip_longest(my_list, my_list[1:]) if i!=j]
    [1, 2, 3, 4, 5, 1, 2]
    

提交回复
热议问题