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