gpt4 book ai didi

python - 查找列表中连续重复数字的最大长度

转载 作者:行者123 更新时间:2023-12-01 23:54:53 25 4
gpt4 key购买 nike

我的问题是如何找到列表中连续重复数字(或一般元素)的最大长度。我编写了以下函数,该函数运行良好,但我想知道是否有更好的方法来执行此操作或改进我的代码。

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 仅重复一次)。

最佳答案

您可以使用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

关于python - 查找列表中连续重复数字的最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com