本文介绍了计算Python中重复序列的最长出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
计算字符串中某个字符的最长连续重复次数的最简单方法是什么?例如以下字符串中最长连续重复的b":
What's the easiest way to count the longest consecutive repeat of a certain character in a string? For example, the longest consecutive repeat of "b" in the following string:
my_str = "abcdefgfaabbbffbbbbbbfgbb"应该是 6,因为其他连续的重复较短(分别为 3 和 2).我如何在 Python 中做到这一点?
would be 6, since other consecutive repeats are shorter (3 and 2, respectively.) How can I do this in Python?
推荐答案一个正则表达式的例子:
How about a regex example:
import re my_str = "abcdefgfaabbbffbbbbbbfgbb" len(max(repile("(b+b)*").findall(my_str))) #changed the regex from (b+b) to (b+b)* # max([len(i) for i in repile("(b+b)").findall(my_str)]) also works编辑,我的与中间人
x=timeit.Timer(stmt='import itertools;my_str = "abcdefgfaabbbffbbbbbbfgbb";max(len(list(y)) for (c,y) in itertools.groupby(my_str) if c=="b")') x.timeit() 22.759046077728271 x=timeit.Timer(stmt='import re;my_str = "abcdefgfaabbbffbbbbbbfgbb";len(max(repile("(b+b)").findall(my_str)))') x.timeit() 8.4770550727844238更多推荐
计算Python中重复序列的最长出现次数
发布评论