You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python统计列表中被分隔的连续相同数字分组出现次数

连续相同数字分组频次统计Python实现

需求说明

统计列表中被其他数字分隔的连续相同数字组成的分组的出现频次。
示例输入:
nums = [3, 1, 2, 3, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 1, 2]
期望输出:
{[3]: 2, [1]: 3, [2]: 5, [1, 1]: 2, [2, 2, 2, 2]: 1}

实现代码

from collections import defaultdict

def count_consecutive_groups(nums):
    if not nums:
        return {}
    count_dict = defaultdict(int)
    current_group = [nums[0]]
    for num in nums[1:]:
        if num == current_group[-1]:
            current_group.append(num)
        else:
            count_dict[tuple(current_group)] += 1
            current_group = [num]
    # 处理遍历结束后剩余的最后一个分组
    count_dict[tuple(current_group)] += 1
    # 转换为列表作为key的格式用于展示,如不需要可直接返回count_dict
    return {list(k): v for k, v in count_dict.items()}

测试调用

nums = [3, 1, 2, 3, 2, 1, 1, 2, 2, 2, 2, 1, 2, 1, 1, 2, 1, 2]
result = count_consecutive_groups(nums)
print(result)

注意事项

  • Python原生字典不支持可变类型(比如列表)作为key,如果你需要对统计结果的key做后续查询、修改等操作,建议保留元组类型的key,删除最后一步的列表转换即可。
  • 代码兼容空列表等边界输入,空输入返回空字典。

内容的提问来源于stack exchange,提问作者Baleweo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:45:04