Replacing Repeating Elements

Question:

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:

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

Asked By: Sarper Makas

||

Answers:

You can use itertools.groupby:

import itertools

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']
Answered By: Johnny Mopp

Alternatively:

arr = ["a", "a", "a", "a", "b", "c", "c", "a"]

cur = arr[0]
count =0
out = []

for i in range(len(arr)):
    if arr[i]== cur:
        count+=1
    else:
        if count == 1:
            out.append(cur)
        else:
            out.append(cur+str(count))
        count=1
        cur = arr[i]        


if(arr[i]==arr[i-1]):
    out.append(cur+str(count))
else:
    out.append(cur)

print(out)

Output:

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

My idea is just to count when the elements are the same, and write to a new array with the previous character and its count when they are different. I need the last if-else to make sure the last set of characters are written.

Answered By: Richard K Yu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.