Remove adjacent element in a list in python

后端 未结 2 667
醉酒成梦
醉酒成梦 2021-01-22 03:11

I am trying to do a simple python program that removes all the adjacent elements in a list

def main():
    a = [1, 5, 2, 3, 3, 1, 2, 3, 5, 6]
    c = len(a)

            


        
2条回答
  •  旧巷少年郎
    2021-01-22 03:51

    Here's a slightly different approach:

    origlist=[1, 5, 2, 3, 3, 1, 2, 3, 5, 6]
    newlist=[origlist[0]]
    for elem in origlist[1:]:
      if (elem != newlist[-1]):
        newlist.append(elem)
    

    The itertools answer above may be preferred, though, for brevity and clarity...

提交回复
热议问题