基于多元组条件的Counter:按Cycle类别统计Transfer出现次数
按Cycle类别统计Transfer出现次数的Python实现
根据你提供的元组遍历输出内容,我先还原了元组的结构,然后整理了几种实用的实现方式:
方法一:基础字典统计(适合新手理解)
这种方法用最基础的字典操作,一步步实现统计逻辑,清晰易懂:
# 还原你的元组结构 my_tup = ( ('Transfer', '0:33:20', 'Cycle 1'), ('Transfer', '0:33:10', 'Cycle 1'), ('Download', '0:09:10', 'Cycle 1'), ('Transfer', '0:33:10', 'Cycle 1'), ('Download', '0:13:00', 'Cycle 1'), ('Download', '0:12:30', 'Cycle 2'), ('Transfer', '0:33:10', 'Cycle 2'), ('Download', '0:02:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:33:00', 'Cycle 2'), ('Transfer', '0:32:40', 'Cycle 2'), ) # 初始化空字典存储统计结果 transfer_counts = {} for item in my_tup: action, _, cycle = item # 只处理Transfer类型的条目 if action == 'Transfer': # 如果当前Cycle还没在字典里,先初始化为0 if cycle not in transfer_counts: transfer_counts[cycle] = 0 transfer_counts[cycle] += 1 print(transfer_counts) # 输出结果: {'Cycle 1': 3, 'Cycle 2': 5}
方法二:用collections.defaultdict简化代码
defaultdict可以自动为不存在的键设置默认值,省去了判断键是否存在的步骤,让代码更简洁:
from collections import defaultdict transfer_counts = defaultdict(int) # 遍历元组,解构每个元素的三个值 for action, _, cycle in my_tup: if action == 'Transfer': transfer_counts[cycle] += 1 # 可选:将defaultdict转为普通字典 transfer_counts = dict(transfer_counts) print(transfer_counts) # 输出结果同样是: {'Cycle 1': 3, 'Cycle 2': 5}
方法三:用collections.Counter快速统计
Counter是专门用于计数的工具类,结合列表推导式可以一行完成过滤和统计,代码最精简:
from collections import Counter # 先过滤出所有Transfer对应的Cycle值,再用Counter统计 transfer_cycles = [cycle for action, _, cycle in my_tup if action == 'Transfer'] transfer_counts = Counter(transfer_cycles) # 转为普通字典输出 print(dict(transfer_counts)) # 输出结果: {'Cycle 1': 3, 'Cycle 2': 5}
这三种方法都能实现你的需求,你可以根据自己的代码习惯选择:如果需要清晰的逻辑就用基础字典,如果想简化代码用defaultdict,如果追求高效简洁就用Counter。
内容的提问来源于stack exchange,提问作者arsenal88
相关产品推荐
相关产品推荐

