0

I have the following list in python3:

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]

I want to have something like this as an output:

b = [1, 2, 3, 1, 2, 4, 3]

How can I do that? I have tried a = set(a) and other methods for getting rid of duplicates. But they remove all duplicates.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Stack_Over
  • 21
  • 1
  • Does this answer your question? [Removing elements that have consecutive duplicates](https://stackoverflow.com/questions/5738901/removing-elements-that-have-consecutive-duplicates) – wjandrea Nov 25 '21 at 21:27
  • BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. In the future, please try some research first. I found that question by googling `python compress adjacent duplicates`. – wjandrea Nov 25 '21 at 21:30

3 Answers3

1

If you are willing to use a module, you can use itertools.groupby:

from itertools import groupby

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]

output = [k for k, _ in groupby(a)]
print(output) # [1, 2, 3, 1, 2, 4, 3]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

This would work:

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
b = [a[0]]
for k in a:
    if k!=b[-1]:
        b.append(k)
print(b)
kpie
  • 9,588
  • 5
  • 28
  • 50
0

If you comfortable with C, you may like this style:

a = [1, 1, 1, 2, 2, 3, 3, 3, 1, 1, 1, 2, 2, 2, 4, 4, 4, 3, 3, 3, 3]
b=len(a)
i=0
last_one=None
while i<b:
    if a[i]==last_one:
        del a[i]
        b-=1
        continue
    else:
        last_one=a[i]
    i+=1
print(a)