Replace duplicate items in a list in Python?

advertisements

For example if I have a list as follows:

[3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]

How can I remove the duplicate elements and represent the same element followed by the number of times it's repeating? Example Output:

[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

Where 3 is repeating 6 times... 1 repeating 6 times... and so on


You can use itertools.groupby with a generator function here:

>>> from itertools import groupby
>>> lst = [3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]
>>> def solve(seq):
    for k, g in groupby(seq):
        length = sum(1 for _ in g)
        if length > 1:
            yield k
            yield length
        else:
            yield  k
...
>>> list(solve(lst))
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]