Python,使用列表,找到最大序列长度

标签 python algorithm list

例如测试列表:

test_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b', 'a', 'a']

对于这个例子,我需要使用什么工具或算法来获得最大序列数:

'a' = 3
'b' = 2
'c = 1

最佳答案

使用 dict 来跟踪最大长度,并且 itertools.groupby按连续值对序列进行分组:

from itertools import groupby

max_count = {}

for val, grp in groupby(test_list):
    count = sum(1 for _ in grp)
    if count > max_count.get(val, 0):
        max_count[val] = count

演示:

>>> from itertools import groupby
>>> test_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b', 'a', 'a']
>>> max_count = {}
>>> for val, grp in groupby(test_list):
...     count = sum(1 for _ in grp)
...     if count > max_count.get(val, 0):
...         max_count[val] = count
... 
>>> max_count
{'a': 3, 'c': 1, 'b': 2}

关于Python,使用列表,找到最大序列长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24410836/

相关文章:

python - 如何识别并正确解析由 Python 创建的 csv 数据中的列表

python - 错误处理,可能缺少变量

python - 为什么不显示 AssertionError?

python - 使用 Matplotlib 绘制数据子集

algorithm - 面积最大化在直方图算法中的应用

在区域内查找三角形的算法

c++ - 具有未知参数 vector 类型的虚函数

python - Odoo 10 - 使用 CRON 的功能

string - 在 MATLAB 中,您可以将字符串视为列表中的一个对象吗?

python - 检查 list.remove(y) 中的 x 是否在一行中