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

如何统计元组列表中的重复项并追加计数为新值

统计元组列表重复项并追加计数的实现

需求说明

给定一个包含重复二元组的列表,需统计每个二元组的出现次数,并将计数作为第三个元素追加到对应元组中,最终输出格式为 [('student', 'department', total count)] 的列表。

输入示例

output = [('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO')]

期望输出

expected_output = [('studentA','ISDF',6), ('studentB','CSE',6),('studentC','BIO',6)]

实现方案

利用Python标准库的collections.Counter可高效完成统计,步骤如下:

  • 用Counter统计输入列表中每个二元组的出现次数
  • 通过列表推导式将二元组与对应计数合并为三元组
  • 转换为目标格式的列表

完整代码

from collections import Counter

# 输入列表
output = [('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO'),('studentA','ISDF'), ('studentB','CSE'),('studentC','BIO')]

# 统计每个元组的出现次数
tuple_counts = Counter(output)

# 生成带计数的三元组列表
result = [(*tpl, count) for tpl, count in tuple_counts.items()]

# 输出结果
print(result)

代码说明

  • Counter(output)会自动遍历列表,统计每个可哈希元素(此处为二元组)的出现次数,返回字典结构的计数器对象
  • 列表推导式[(*tpl, count) ...]通过解包二元组tpl并追加计数count,生成符合要求的三元组
  • 最终result即为期望的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:35:21