pack consecutive duplicates of list elements into sublists python

Solutions on MaxInterview for pack consecutive duplicates of list elements into sublists python by the best coders in the world

showing results for - "pack consecutive duplicates of list elements into sublists python"
Johanna
18 Aug 2019
1import itertools
2
3def pack_consecutive_duplicates(_list: list):
4    preprocessed_list = []
5    # x groups the duplicates into a tuple ()
6    # x[0] is the duplicate element
7    # x[1] is a grouper iterable that conatins all the duplicate elements
8    for x in itertools.groupby(_list):
9        amount = [*x[1]].count(x[0])
10        if amount > 1:
11            for k in range(0, amount):
12                preprocessed_list.append(x[0])
13        else:
14            preprocessed_list.append((x[0]))
15
16    return preprocessed_list