使用groupby,它按值对元素进行分组:
from itertools import groupbygroup = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1])print max(group, key=lambda k: len(list(k[1])))
这是运行中的代码:
>>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1])>>> print max(group, key=lambda k: len(list(k[1])))(2, <itertools._grouper object at 0xb779f1cc>)>>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3])>>> print max(group, key=lambda k: len(list(k[1])))(3, <itertools._grouper object at 0xb7df95ec>)
从python文档中:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
如果您还希望索引的运行时间最长,则可以执行以下 *** 作:
group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3])result = []index = 0for k, g in group: length = len(list(g)) result.append((k, length, index)) index += lengthprint max(result, key=lambda a:a[1])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)