如何创建非唯一键的Python字典?解决课程成绩与学分计算问题
解决重复成绩存储与对应元素相乘的问题
首先得明确:Python里的字典天生要求键唯一,没办法直接让字典支持重复键——这是字典的设计特性。所以咱们得换个思路来存储数据,同时解决遍历相乘的问题。下面给你两种实用的方案:
方案一:用列表存储(成绩, 学分)元组(最推荐)
既然字典不适合存重复键的数据,咱们直接用列表来保存每一门课程的成绩和学分对,这样既保留所有数据,又能轻松遍历计算。
修改后的代码如下:
course_list = [] while True: score_input = input("Enter score (enter -1 to finish): ") if score_input == '-1': break # 注意把成绩转成数字(整数或浮点数,根据你的需求) score = float(score_input) unit_load = int(input("Enter unit load: ")) # 把每一组数据存成元组,添加到列表里 course_list.append( (score, unit_load) ) last_list = [] for score, unit_load in course_list: multiple = score * unit_load last_list.append(multiple) print("成绩×学分的结果列表:", last_list)
这个方案的好处是:
- 完全保留所有课程数据,不管成绩是否重复
- 遍历的时候直接拆包元组,逻辑清晰,不容易出错
- 修正了你原代码里的一个小问题:原代码中
score是字符串类型,直接和unit_load相乘会报错,这里转成了浮点数(如果是整数成绩可以用int())
方案二:用字典存储,把重复成绩的学分存为列表(适合需要按成绩分组的场景)
如果你确实需要用字典结构,比如后续要按成绩统计学分总和,可以把字典的值改成列表,这样同一个成绩对应的所有学分都存在列表里。
代码示例:
score_unit_dict = {} while True: score_input = input("Enter score (enter -1 to finish): ") if score_input == '-1': break score = float(score_input) unit_load = int(input("Enter unit load: ")) # 如果成绩已经在字典里,就把学分追加到列表;否则新建键值对 if score in score_unit_dict: score_unit_dict[score].append(unit_load) else: score_unit_dict[score] = [unit_load] last_list = [] for score, unit_loads in score_unit_dict.items(): # 遍历每个成绩对应的学分列表,分别计算乘积 for unit in unit_loads: multiple = score * unit last_list.append(multiple) print("成绩×学分的结果列表:", last_list)
这个方案适合需要对相同成绩做后续处理的场景,但如果只是单纯计算每门课的成绩×学分,方案一更直接。
补充:关于你尝试的双列表方案
如果你想用两个列表分别存成绩和学分,也可以实现,只需要用zip()函数把两个列表配对遍历:
score_list = [] unit_list = [] while True: score_input = input("Enter score (enter -1 to finish): ") if score_input == '-1': break score = float(score_input) unit_load = int(input("Enter unit load: ")) score_list.append(score) unit_list.append(unit_load) last_list = [] # 用zip把两个列表的对应元素配对 for score, unit_load in zip(score_list, unit_list): multiple = score * unit_load last_list.append(multiple) print("成绩×学分的结果列表:", last_list)
这个方案和方案一类似,只是把数据拆成了两个列表,用zip()来关联对应位置的元素。
总结一下:如果只是需要保留所有课程数据并计算每门课的乘积,方案一(列表存元组)是最简洁直观的选择;如果有按成绩分组的需求,再考虑方案二。
内容的提问来源于stack exchange,提问作者honesty20
相关产品推荐
相关产品推荐

