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 ?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With