0

I have a list like the following

a = [5,5,5,5,3,3,2,2,2,2,5,5,5,2,2,2,2,2]

I wish to have the following output list

b = [5,3,2,5,2]

Note that I have tried using

list(OrderedDict.fromkeys(a))

which gives me

[5, 3, 2]

Notice that it does not consider the 2nd 5 or the 2nd 2 as they are non-unique by then.

I need a way to make the machine understand that as and when it encounters a unique element (say the first '5'), it should store it in list b. Consequently, when it encounters the first '3' or first '2', it should store them in list b as well. No problems until this point. As it encounters the second set of '5's, it should store that 5 as a new element in list b. Same goes for the second set of 2's.

Is there a Pythonic way to do this?

Debjit Bhowmick
  • 920
  • 7
  • 20

2 Answers2

5

Other than just doing a for loop you could use itertools groupby:

import itertools

a = [5,5,5,5,3,3,2,2,2,2,5,5,5,2,2,2,2,2]
b = [x[0] for x in itertools.groupby(a)]  # [5, 3, 2, 5, 2]

Documentation for this can be found here: https://docs.python.org/3/library/itertools.html#itertools.groupby

EDIT: Some clarification. The reason this is able to count re-occurrences in the list is explained by this paragraph in the documentation (emphasis mine):

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes [...]

ricekab
  • 630
  • 5
  • 17
0

Bro u solve this problem without any iterator using list comprehensive

a = [5,5,5,5,3,3,2,2,2,2,5,5,5,2,2,2,2,2]
b = [a[i] for i in range(len(a)) if a[i]! = a[i-1]]
Print(b)
Output is b = [5,3,2,5,2]