Python统计列表元素匹配字典键更新计数及历史值存储问题
现有代码问题说明
- 定义list_1、list_2、list_3时A、B、C未加引号,属于未定义变量,运行会报错;ABC_dictionary中C的键为小写
'c',和元素大写'C'不匹配,无法统计到C的计数。 - 循环中使用
zip(list, ABC_dictionary.keys())完全多余,且会导致遍历不全,不需要和字典键配对遍历。 - 每次匹配到元素都执行
update({'count' : 0}),会强制重置计数,导致上一次的统计结果被覆盖。 - 原始字典中B、C、D的
name字段均错误写为'A',属于笔误,建议修正。
解决方案
方案1:每次统计结果独立存储到列表(推荐,和你期望的输出格式完全匹配)
该方案会为每个输入列表生成一份独立的统计字典,全部存入结果列表,后续可以直接按索引调取对应列表的统计结果做计算。
from copy import deepcopy # 原始输入数据,字符串统一加引号,元素C为大写 list_1 = ('A','B','C') list_2 = ('A','A','B','B','C','C') list_3 = ('A','A','A','B','B','B','C','C','C') lists = [list_1, list_2, list_3] # 统计模板字典,修正C键为大写、各name字段为对应值 abc_template = { 'A': {'name': 'A', 'MW': 5}, 'B': {'name': 'B', 'MW': 6}, 'C': {'name': 'C', 'MW': 7}, 'D': {'name': 'D', 'MW': 8} } # 存储所有列表的统计结果 all_stat_results = [] for current_list in lists: # 深拷贝模板,避免修改原始模板,也避免各次统计结果互相影响 current_stat = deepcopy(abc_template) for key in current_stat: # 直接统计当前键在本次列表中的出现次数 current_stat[key]['count'] = current_list.count(key) all_stat_results.append(current_stat)
调用示例
# 调取第2个列表(索引为1)的A重量计算 A_weight = all_stat_results[1]['A']['MW'] * all_stat_results[1]['A']['count']
all_stat_results的内容和你期望的每个列表输出完全一致,索引0对应list_1、1对应list_2、2对应list_3。
方案2:所有历史计数存储在同一个字典中
如果需要把所有统计值存在同一份字典里,可以把count字段改为列表,按顺序存储每个列表的统计值:
list_1 = ('A','B','C') list_2 = ('A','A','B','B','C','C') list_3 = ('A','A','A','B','B','B','C','C','C') lists = [list_1, list_2, list_3] abc_dictionary = { 'A': {'name': 'A', 'MW': 5, 'count_history': []}, 'B': {'name': 'B', 'MW': 6, 'count_history': []}, 'C': {'name': 'C', 'MW': 7, 'count_history': []}, 'D': {'name': 'D', 'MW': 8, 'count_history': []} } for current_list in lists: for key in abc_dictionary: abc_dictionary[key]['count_history'].append(current_list.count(key))
调用示例
# 调取第1个列表(索引为0)的A重量计算 A_weight = abc_dictionary['A']['MW'] * abc_dictionary['A']['count_history'][0]
内容的提问来源于stack exchange,提问作者Edwin OA
相关产品推荐
相关产品推荐

