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

如何统计列表元素出现次数并生成含元素与次数的新列表?

统计列表元素出现次数的几种实现方法

方法1:用标准库collections.Counter(最简便)

这是Python官方提供的频次统计工具,能快速完成统计,直接转成你需要的元素-次数tuple列表:

from collections import Counter

original_list = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'D']
# 统计各元素出现频次
count_counter = Counter(original_list)
# 转成(元素, 次数)的tuple列表
result_list = list(count_counter.items())

print(result_list)
# 输出: [('A', 3), ('B', 3), ('C', 2), ('D', 2)]

方法2:手动统计(不依赖标准库)

如果不想用库,用字典手动遍历统计,再转成tuple列表:

original_list = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'D']
count_dict = {}

for item in original_list:
    # 元素存在则计数+1,不存在则初始化为1
    count_dict[item] = count_dict.get(item, 0) + 1

result_list = list(count_dict.items())
print(result_list)

方法3:用自定义类存储(结构化对象)

如果需要更清晰的结构化存储(而非tuple),可以自定义类封装元素和次数:

class ElementCount:
    def __init__(self, element, count):
        self.element = element
        self.count = count
    
    # 自定义打印格式,方便查看结果
    def __repr__(self):
        return f"ElementCount(element='{self.element}', count={self.count})"

original_list = ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'D', 'D']
count_dict = {}
for item in original_list:
    count_dict[item] = count_dict.get(item, 0) + 1

# 生成自定义对象列表
result_list = [ElementCount(elem, cnt) for elem, cnt in count_dict.items()]
print(result_list)
# 输出: [ElementCount(element='A', count=3), ElementCount(element='B', count=3), ElementCount(element='C', count=2), ElementCount(element='D', count=2)]

额外:对结果排序

如果需要按次数排序(比如从多到少):

# 针对tuple列表的排序
sorted_result = sorted(result_list, key=lambda x: x[1], reverse=True)

# 针对自定义类列表的排序
sorted_result = sorted(result_list, key=lambda x: x.count, reverse=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:10:20