Removing elements that have consecutive duplicates

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

提交回复
热议问题