簡體   English   中英

如何在python中查找數字的最大連續出現次數

[英]How to find the maximum consecutive occurrences of a number in python

我想找出python中連續出現的數字的最大數量。 我從堆棧溢出使用以下代碼。

from itertools import groupby
b= [1,2,45,55,5,4,3,2,5,5,6,5456,5456,5456,7,67,6,6]

print(b)

def occurrence():
    occurrence, num_times = 0, 0
    for key, values in groupby(b, lambda x : x):
        val = len(list(values))
        if val >= occurrence:
            occurrence, num_times =  key, val
    return occurrence, num_times

occurrence, num_times = occurrence()
print("%d occurred %d times" % (occurrence, num_times))

我得到以下答案:

5 occurred 2 times

答案應該是5456,因為它發生了3次。 任何人都可以幫我解決這個問題嗎?

你唯一需要改變的是

if val >= num_times:

您的代碼正在比較當前組的長度和最后一個key

此方法返回的最大連續出現的最后一個項目(如果有三次5中,這將被選擇的列表更高版本)。

您可以使用內置的max函數來簡化代碼,以查找最大num_times

from itertools import groupby

b = [1, 2, 45, 55, 5, 4, 3, 2, 5, 5, 6, 5456, 5456, 5456, 7, 67, 6, 6]

num_times, occurrence = max((len(list(values)), key) for key, values in groupby(b))
print("%d occurred %d times" % (occurrence, num_times))

產量

5456 occurred 3 times

沒有必要給groupby提供低效的lambda x: x :如果你沒有給它一個關鍵函數,它默認使用identity函數。


FWIW,有一種更有效的方法來計算groupby組的長度。 這里並不重要,但是當團體很大時它很方便。 我們可以循環遍歷組並使用內置sum來計算組中的項目,而不是將組轉換為列表並獲取其長度。 只是改變

len(list(values))

sum(1 for _ in values)

您可以使用以下生成器表達式:

print('{1} occurred {0} times'.format(*max((len(list(g)), k) for k, g in groupby(b))))

這輸出:

5456 occurred 3 times

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM