Home > Mobile >  Replacing Repeating Elements
Replacing Repeating Elements

Time:01-10

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

CodePudding user response:

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']

CodePudding user response:

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.

  • Related