您如何计算列表中的最大重复次数? [英] How do you calculate the greatest number of repetitions in a list?

查看:142
本文介绍了您如何计算列表中的最大重复次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有类似Python的列表

If I have a list in Python like

[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]

如何计算任何元素的最大重复数?在这种情况下,2最多重复4次,1最多重复3次.

How do I calculate the greatest number of repeats for any element? In this case 2 is repeated a maximum of 4 times and 1 is repeated a maximum of 3 times.

是否有办法做到这一点,但还可以记录运行时间最长的索引?

Is there a way to do this but also record the index at which the longest run began?

推荐答案

使用 groupby ,它按值对元素进行分组:

Use groupby, it group elements by value:

from itertools import groupby
group = 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文档:

From python documentation:

groupby()的操作类似 到Unix中的uniq过滤器.它 每产生一个休息或新的小组 时间键功能的值 变化

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes

# [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

如果您还希望运行时间最长的索引,可以执行以下操作:

If you also want the index of the longest run you can do the following:

group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3])
result = []
index = 0
for k, g in group:
   length = len(list(g))
   result.append((k, length, index))
   index += length

print max(result, key=lambda a:a[1])

这篇关于您如何计算列表中的最大重复次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆