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

如何对数组中相同元素进行分组并统计数量?

数组重复元素分组与计数的实现方法

针对数组重复元素的分组和计数需求,有几种实用的实现方式,具体如下:

方法一:使用collections.Counter(推荐)

Python标准库的collections.Counter就是专门用来统计可迭代对象元素出现次数的工具,用法简单直接:

from collections import Counter

A = [1,1,2,2,2,4,5,6,6,6]
count_result = Counter(A)
print(count_result)
# 输出:Counter({2: 3, 6: 3, 1: 2, 4: 1, 5: 1})

如果需要更通用的格式,可转成字典或列表:dict(count_result) 或 list(count_result.items())。

方法二:手动遍历统计

不想依赖标准库的话,自己写循环也能实现,适合理解底层逻辑:

A = [1,1,2,2,2,4,5,6,6,6]
count_dict = {}
for num in A:
    if num in count_dict:
        count_dict[num] += 1
    else:
        count_dict[num] = 1
print(count_dict)
# 输出:{1: 2, 2: 3, 4: 1, 5: 1, 6: 3}

方法三:使用itertools.groupby(适合有序数组)

如果你的数组是有序的(相同元素连续排列),用itertools.groupby分组计数效率很高:

from itertools import groupby

A = [1,1,2,2,2,4,5,6,6,6]
count_result = {key: len(list(group)) for key, group in groupby(A)}
print(count_result)
# 输出:{1: 2, 2: 3, 4: 1, 5: 1, 6: 3}

注意:如果数组无序,groupby会把不连续的相同元素当成不同组,使用前需要先排序,比如传入sorted(A)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 22:35:19