Skip to content Skip to sidebar Skip to footer

How To Keep Unique Items From A Collection Of Similar Items In A List?

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

Solution 1:

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 [...]

Solution 2:

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 inrange(len(a)) if a[i]! = a[i-1]]
Print(b)
Output is b = [5,3,2,5,2]

Post a Comment for "How To Keep Unique Items From A Collection Of Similar Items In A List?"