使用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
廣告