0

I have list below.

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

I want to drop overlapping, but preserve the order of appearance. So I want to get list like

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

I don't drop all overlapping (want to drop if next or previous value is the same as previous or next value).

How can I write the code to get that list ?

1 Answers1

3

Use itertools.groupby:

[k for k, _ in groupby(a)]

Example:

from itertools import groupby

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

print([k for k, _ in groupby(a)])
# [4, 1, 2, 3, 1]
Austin
  • 25,759
  • 4
  • 25
  • 48