计算Python中重复序列的最长出现次数

编程入门 行业动态 更新时间:2024-10-27 00:34:43
本文介绍了计算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中重复序列的最长出现次数

本文发布于:2023-11-29 00:10:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644512.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   最长   次数   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!