-1

I have a Python list of strings such that,

Input:

li = ['aaa','bbb','aaa','abb','abb','bbb','bbb','bbb','aaa','aaa']

What can I do to generate another list counting the number of consecutive repetitions of any string in the list? For the list above the return list resembles:

Expected Output:

li_count = [['aaa',1],['bbb',1]['abb',2],['bbb',3],['aaa',2]]
swopnil
  • 347
  • 1
  • 3
  • 11
  • 1
    Didn't you forget the second, not duplicated 'aaa'? `li_count = [['aaa',1],['bbb',1],['aaa',1],['abb',2],['bbb',3],['aaa,2]]` should be correct. And please, show what your attempts look like so far and why do they not work. – SpghttCd Jun 13 '18 at 05:08

1 Answers1

8

Use itertools.groupby:

from itertools import groupby
li = ['aaa','bbb','aaa','abb','abb','bbb','bbb','bbb','aaa','aaa']

a = [[i, sum(1 for i in group)] for i, group in groupby(li)]
print(a)
[['aaa', 1], ['bbb', 1], ['aaa', 1], ['abb', 2], ['bbb', 3], ['aaa', 2]]

Thank you @user3483203 for improvement:

a = [[i, len([*group])] for i, group in groupby(li)]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 3
    It is a lot faster here to use `[[i, len([*group])] for i, group in groupby(li)]`. About twice as fast as `sum` – user3483203 Jun 13 '18 at 05:16