Replacing Repeating Elements

I have a list that’s include repetitive elements. I need to change repetitive elements to ElementNameElementNum.


["a", "a", "a", "a", "b", "b", "b", "c", "c", "a"]

How can I change this array to:

["a4", "b3", "c2", "a"] 

There is 4 a that is repeating, 3 b and 2 c is repeating back to back too. But last a is not repeating so it will stay as "a".

>Solution :

You can use itertools.groupby:

lst = ["a", "a", "a", "a", "b", "b", "b", "c", "c", "a"]
result = []
for item, group in itertools.groupby(lst):
    count = sum(1 for _ in group)
    result.append(f"{item}{count}" if count > 1 else item)


['a4', 'b3', 'c2', 'a']

Leave a Reply