Removing elements that have consecutive duplicates

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

    Plenty of better/more pythonic answers above, however one could also accomplish this task using list.pop():

    my_list = [1, 2, 3, 3, 4, 3, 5, 5]
    for x in my_list[:-1]:
        next_index = my_list.index(x) + 1
        if my_list[next_index] == x:
            my_list.pop(next_index)
    

    outputs

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

    Oneliner in pure Python

    [v for i, v in enumerate(your_list) if i == 0 or v != your_list[i-1]]
    
    0 讨论(0)
  • 2020-11-22 10:33
    >>> L = [1,1,1,1,1,1,2,3,4,4,5,1,2]
    >>> from itertools import groupby
    >>> [x[0] for x in groupby(L)]
    [1, 2, 3, 4, 5, 1, 2]
    

    If you wish, you can use map instead of the list comprehension

    >>> from operator import itemgetter
    >>> map(itemgetter(0), groupby(L))
    [1, 2, 3, 4, 5, 1, 2]
    

    For the second part

    >>> [x for x, y in groupby(L) if len(list(y)) < 2]
    [2, 3, 5, 1, 2]
    

    If you don't want to create the temporary list just to take the length, you can use sum over a generator expression

    >>> [x for x, y in groupby(L) if sum(1 for i in y) < 2]
    [2, 3, 5, 1, 2]
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
  • 2020-11-22 10:36

    You can do this by using zip_longest() + list comprehension.

    from itertools import zip_longest 
    list1 = [1, 2, 3, 3, 4, 3, 5, 5].
         # using zip_longest()+ list comprehension       
         res = [i for i, j in zip_longest(list1, list1[1:]) 
                                                                if i != j] 
            print ("List after removing consecutive duplicates : " +  str(res)) 
    
    0 讨论(0)
提交回复
热议问题