我有以下字符串:
"TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"
我希望能够将T分组列入一个列表,然后将T的数量计入第一个H.
即。
[3, 1, 2, 4, 3, 6, 5, 1]
在python中最有效的方法是什么?
答案 0 :(得分:8)
itertools.groupby
是你的朋友
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]
答案 1 :(得分:5)
您可以使用列表解析在一行中执行此操作:
my_string = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"
my_list = [len(i) for i in my_string.split('H') if len(i)>0]
my_list
的输出:
[3, 1, 2, 4, 3, 6, 5, 1]
答案 2 :(得分:0)
您可以使用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
给出:
counts
=> [3, 1, 2, 4, 3, 6, 5, 1]
答案 3 :(得分:0)
另一种使用列表理解的方法:
my_string = "TTTHTHTTHTTTTHTTTHTTTTTTHTTTTTHTH"
strips = my_string.strip('H')
splits = strips.split('H' )
# generating iterables of 1 and then summation
my_list = [sum(1 for i in j) for j in splits]
print(my_list )
给予
[3, 1, 2, 4, 3, 6, 5, 1]
[Program finished]