-1

I have a list of strings and numbers l = ['a','a',9,7,'b','c','c','c']

And the output wanted is ['a*2',9,7,'b','c*3']

This is what I have but it can only do '*2' and the last element is not affected by this

    a = ['a','a',9,7,'b','c','c','c']
    i = 0 
    while i < len(a)-1:
            
        if a[i] != a[i+1]:
            a[i]=str(a[i]).replace(' ','') + '*1 '
            i += 1
        
        elif a[i] == a[i+1]:
            del a[i+1]
            a[i]=str(a[i]).replace(' ','') + '*2 '
            i += 1
    print(a)

How can I do this ?

Thibaultofc
  • 29
  • 10
  • `from itertools import groupby; [i[0] if i[1] == 1 else '%s*%d' % i for i in [(k, len(list(v))) for k, v in groupby(a)]]`. – ekhumoro Oct 24 '20 at 20:26

1 Answers1

0

Using a simple loop should do the trick.

a =  ['a','a',9,7,'b','c','c','c','d']
i = 0
n = len(a)
ans = []
while i<n:
    j = i+1
    while j<n and a[j]==a[i]:
        j += 1
    if j-i==1:
        ans.append(a[i])
    else:
        ans.append(str(a[i])+"*"+str(j-i))
    i=j
print(ans)  # prints ['a*2', 9, 7, 'b', 'c*3']
Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24
  • Thank you but the problem is that set removes any duplicates and if for example a=['a','b','b','a','b'] I need it to output ['a','b*2','a','b'] – Thibaultofc Oct 24 '20 at 20:23