按Age字段分组字典列表时遇索引越界问题求助
按年龄分组字典列表的问题解决
需求说明
需要将包含个人信息的字典列表按Age字段分组,输出15至22岁各年龄段对应的字典集合:
- 输入字典示例:
[ {'School': 'GP', 'Age': '18', 'StudyTime': '2', 'Failures': '0', 'Health': '3', 'Absences': '6', 'G1': '5', 'G2': '6', 'G3': '6'}, # 更多字典... ]
- 期望输出格式:
Range for age is 15 to 22 { 15 : [ {'School': 'GP', 'StudyTime': 4.2, 'Failures': 3, 'Health': 3, 'Absences': 6, 'G1': 7, 'G2': 8, 'G3': 10 }, # 其他字典... ], 16 : [ {'School': 'MS', 'StudyTime': 1, 'Failures': 1.2, 'Health': 4, 'Absences': 10, 'G1': 9, 'G2': 11, 'G3': 7 }, # 其他字典... ], # 更多年龄段... }
错误代码与问题分析
尝试的代码出现索引越界错误:
age_list = [15,16,17,18,19,20,21,22] # dict_list 是需要分组的字典列表 res = defaultdict(list) for i in age_list: for j in dict_list: if age_list[i] == j['Age']: res[i].append(j) print(res)
错误原因:
- 索引越界:
for i in age_list循环中,i是具体的年龄值(如15、16),而非列表索引。age_list[i]试图用年龄值作为索引访问列表,而age_list的最大索引是7,远小于15,直接导致索引越界。 - 类型不匹配:字典中的
Age字段是字符串类型(如'18'),而i是整数类型,两者比较永远不相等,无法匹配数据。
修正后的代码
from collections import defaultdict # 定义目标年龄范围 age_list = [15,16,17,18,19,20,21,22] # 示例字典列表(替换为你的实际数据) dict_list = [ {'School': 'GP', 'Age': '18', 'StudyTime': '2', 'Failures': '0', 'Health': '3', 'Absences': '6', 'G1': '5', 'G2': '6', 'G3': '6'}, {'School': 'MS', 'Age': '16', 'StudyTime': '1', 'Failures': '1', 'Health': '4', 'Absences': '10', 'G1': '9', 'G2': '11', 'G3': '7'}, {'School': 'GP', 'Age': '15', 'StudyTime': '4', 'Failures': '3', 'Health': '3', 'Absences': '6', 'G1': '7', 'G2': '8', 'G3': '10'} ] res = defaultdict(list) # 遍历每个字典,按年龄分组 for item in dict_list: # 将字符串类型的Age转为整数,避免类型不匹配 current_age = int(item['Age']) # 仅处理目标年龄范围内的数据 if current_age in age_list: res[current_age].append(item) # 确保所有目标年龄都出现在结果中(即使没有对应数据) for age in age_list: if age not in res: res[age] = [] # 按要求格式输出 print("Range for age is 15 to 22") print(res)
优化建议
- 可以用
range(15, 23)代替手动书写age_list,自动生成15至22的整数序列:age_list = list(range(15, 23)) - 如果需要将字典中的数值字段(如
StudyTime、G1等)转为数值类型,可以在添加到结果前统一处理,匹配期望输出的格式。
内容的提问来源于stack exchange,提问作者Deep
相关产品推荐
相关产品推荐

