Remove adjacent element in a list in python

后端 未结 2 666
醉酒成梦
醉酒成梦 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:38
    for i in range (0, c-2):
    

    This is not like a for loop in some other languages; it’s iterating over a list returned (once) by range. When you change c later, it does not affect this loop.

    You can use while instead:

    c = len(a)
    
    while i < c - 2:
        if a[i] == a[i + 1]:
            del a[i]
            c = len(a)
        else:
            i += 1
    

    There’s also itertools.groupby:

    import itertools
    
    def remove_consecutive(l):
        return (k for k, v in itertools.groupby(l))
    
    0 讨论(0)
  • 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...

    0 讨论(0)
提交回复
热议问题