在列表中找到连续重复数字的最大长度

3

我的问题是如何找到列表中连续重复数字(或元素)的最大长度。我编写了以下函数,它可以正常工作,但我想知道是否有更好的方法来完成这个任务或者可以改进我的代码。

def longest(roll):
    '''Return the maximum length of consecutive repeated elements in a list.'''
    i = 0
    M = 0   # The maximum length
    while 0 <= i < len(roll):
        c = 1  # Temporarily record the length of consecutive elements
        for j in range(i+1, len(roll)):
            if roll[j] != roll[i]:
                i = j
                break
            c += 1
            i += 1    
        if c > M:
            M = c
        if i == len(roll) - 1:
            break
    return M  

我所说的最大长度是指以下情况:
[1, 1, 2, 2, 2, 4] 应该返回 3(数字 2 重复了 3 次);
[1, 2, 1, 2, 1] 应该返回 1(数字 1 和 2 只重复了一次)。
2个回答

8
你可以使用 itertools 模块。
In [8]: import itertools

In [9]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]

In [10]: z
Out[10]: [(1, 2), (2, 3), (3, 1)]

元组以 (item, count) 格式表示。如果有多个给定数字的连续序列,它们将被相应地分组。请参见下文。

In [11]: a = [1,1,1,1,1,2,2,2,2,2,1,1,1,3,3]

In [12]: z = [(x[0], len(list(x[1]))) for x in itertools.groupby(a)]

In [13]: z
Out[13]: [(1, 5), (2, 5), (1, 3), (3, 2)]

从这里获取最大值并不难。
In [15]: max(z, key=lambda x:x[1])[1]
Out[15]: 5

0
longest_fragment = 0
current_fragment = 0

a = int(input())
last_input = a # why do I assign last_input here?
while a:
    if a == last_input:
        current_fragment += 1
    else:  # why is current_fragment assigned 1 in this clause?
        if current_fragment > longest_fragment:
            longest_fragment = current_fragment
            current_fragment = 1
    last_input = a
    a = int(input())

longest_fragment = max(longest_fragment, current_fragment) 
# why didn't i use max in the loop?
# why am I checking again down here anyway?

print('The longest fragment was:', longest_fragment)

希望这可以解决问题,但请附上代码的解释,以便用户真正理解他/她想要的内容。 - Jaimil Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接