python字符串中连续相同字符个数
由字符TF组成的字符串,如:'TTFTTTFFFFTFFTT'能计算连续相同字符的个数,如返回:T2,F1,T3,F4,T1,F2,T2另外求得出如下结果的方案['TT'...
由字符TF组成的字符串,如:'TTFTTTFFFFTFFTT'
能计算连续相同字符的个数,如返回:T2, F1, T3, F4, T1, F2, T2
另外求得出如下结果的方案['TT', 'F', 'TTT', 'FFFF', 'T', 'FF', 'TT']
请尽量pythonic 展开
能计算连续相同字符的个数,如返回:T2, F1, T3, F4, T1, F2, T2
另外求得出如下结果的方案['TT', 'F', 'TTT', 'FFFF', 'T', 'FF', 'TT']
请尽量pythonic 展开
5个回答
展开全部
def countSeq(TF):
result = []
if TF is None or len(TF) == 0:
return result
pattern = TF[0]
count = 1
for s in TF[1:]:
if s == pattern:
count += 1
else:
result.append(pattern + str(count))
pattern = s
count = 1
result.append(pattern + str(count))
return result
def printSeq(TF):
result = []
if TF is None or len(TF) == 0:
return result
pattern = TF[0]
result.append(pattern)
for s in TF[1:]:
if s == pattern:
result[-1] += s
else:
pattern = s
result.append(pattern)
return result
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
import itertools
l = [(k, len(list(g))) for k, g in itertools.groupby('TTFTTTFFFFTFFTT')]
l:[('T', 2), ('F', 1), ('T', 3), ('F', 4), ('T', 1), ('F', 2), ('T', 2))]
不要重复造轮子
l = [(k, len(list(g))) for k, g in itertools.groupby('TTFTTTFFFFTFFTT')]
l:[('T', 2), ('F', 1), ('T', 3), ('F', 4), ('T', 1), ('F', 2), ('T', 2))]
不要重复造轮子
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
a='TTFTTTFFFFTFFTT'
["%s=%d"%(x,a.count(x)) for x in set(a)]
["%s=%d"%(x,a.count(x)) for x in set(a)]
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
下面这个解法应该足够 pythonic 了:
# -*- coding: utf-8 -*-
def split_seq(s):
import re
# sep shouldn't conflict with any substring in s, so we make it a little weird ~
sep = '<[|]>'
separated_s = re.sub(r'(.)\1*', lambda m: m.group(0)+sep, s)
return separated_s.split(sep)[:-1]
def count_seq(s):
lst = split_seq(s)
return [(s[0],len(s)) for s in lst]
s = 'TTFTTTFFFFTFFTT'
print(split_seq(s))
print(count_seq(s))
# ==================== the result ====================
# ['TT', 'F', 'TTT', 'FFFF', 'T', 'FF', 'TT']
# [('T', 2), ('F', 1), ('T', 3), ('F', 4), ('T', 1), ('F', 2), ('T', 2)]
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询