Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing Repeating Elements

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

Example:

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

How can I change this array to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["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)
print(result)

Output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading