Group one character otherwise

I have the following line:

"TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"

I would like to be able to group T into a list, and then count the number T to the first H.

i.e. so that

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

What is the most efficient way to do this in python?

+4
source share
3 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]
+8
source

You can do this on a single line with a list:

my_string = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"
my_list = [len(i) for i in my_string.split('H') if len(i)>0]

Conclusion my_list:

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

You can achieve this with itertools:

import itertools
s = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"
counts = []
count = 1
for a, b in zip(s, s[1:]):
    if a==b:
        count += 1
    elif a == "T":
        counts.append(count)
        count = 1

gives:

   counts
=> [3, 1, 2, 4, 3, 6, 5, 1]
0
source

Source: https://habr.com/ru/post/1682907/


All Articles