Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by a single character otherwise split

I have the following string:

"TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"

I would like to be able to group by the T's into a list and then count the number of T's to the first H.

i.e. so like

[3, 1, 2, 4, 3, 6, 5, 1]

Whats the most efficient way to do this in python ?

like image 412
Tim Avatar asked Dec 07 '22 17:12

Tim


1 Answers

itertools.groupby is your friend

from itertools import groupby

s = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"

res = [sum(1 for _ in g) for k, g in groupby(s) if k == 'T']
print(res)

# [3, 1, 2, 4, 3, 6, 5, 1]
like image 102
Steven Summers Avatar answered Dec 10 '22 06:12

Steven Summers