使用map函数在Python中查找二进制字符串中连续1的最大长度


有时在处理数字的二进制表示时,我们可能需要找出数字中存在多少个连续的1。本文介绍了两种查找方法。

使用split和map

python中的split函数可以用于将给定的字符串分割成多个字符串。我们用零分割它,并使用map函数查找生成的分割中最大长度。

示例

 在线演示

data = '11110000111110000011111010101010101011111111'
def Max_len_cons_1(data):
print ("Maximum Number of consecutive one's: ",max(map(len,data.split('0'))) )
Max_len_cons_1(data)

输出

运行以上代码,我们得到以下结果:

Maximum Number of consecutive one's: 8

使用正则表达式

python中的re模块也可以用来计算连续1的最大数量。这里我们找到1+的模式,它表示一个或多个1的存在。然后找到这些模式中的最大长度。

示例

 在线演示

data = '11110000111110010011'
import re
the_ones = re.findall(r"1+", data)
print("The blocks of one's: ",the_ones)
print("Maximum Number of consecutive one's =", len(max(the_ones, key=len)))

输出

运行以上代码,我们得到以下结果:

The blocks of one's: ['1111', '11111', '1', '11']
Maximum Number of consecutive one's = 5

更新于:2020年2月4日

383 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.