Python中比较两个列表元素及处理学生作业提交数据的方法
嘿,我来帮你解决这两个Python问题,一步步给你讲清楚:
问题1:如何在Python中比较两个列表的元素?
根据不同的需求,有几种常用的方法,我给你拆分说明:
判断两个列表是否完全一致(顺序和元素都相同):直接用
==运算符就能搞定,它会逐一对比每个位置的元素。list1 = [1, 2, 3] list2 = [1, 2, 3] print(list1 == list2) # 输出 True list3 = [3, 2, 1] print(list1 == list3) # 输出 False(顺序不一样)判断两个列表是否包含相同元素(考虑重复次数,不考虑顺序):如果不需要管重复次数,把列表转成集合后比较就行;如果要考虑元素重复的次数,就用
collections.Counter统计每个元素的出现次数再对比:from collections import Counter list4 = [1, 2, 2, 3] list5 = [2, 1, 3, 2] print(Counter(list4) == Counter(list5)) # 输出 True(重复次数一致) list6 = [1, 2, 3] print(Counter(list4) == Counter(list6)) # 输出 False(重复次数不同)找两个列表的共同元素:用集合的交集操作
set(list1) & set(list2),或者用列表推导式[x for x in list1 if x in list2](后者会保留原列表里的重复元素)。找两个列表的差异元素:用集合的差集
set(list1) - set(list2)(得到list1有但list2没有的元素),或者对称差集set(list1) ^ set(list2)(得到两边独有的元素)。
问题2:如何合并两个文件的学生信息生成指定输出?
这个需求可以通过读取文件、构建字典存储信息,再拼接内容来实现,我给你写个完整的代码示例,再拆解步骤:
# 第一步:读取a1.txt,构建学生ID到作业成绩的字典 score_map = {} with open('a1.txt', 'r', encoding='utf-8') as score_file: for line in score_file: cleaned_line = line.strip() if not cleaned_line: # 跳过空行 continue # 分割ID和成绩,去掉多余空格 student_id, score = [part.strip() for part in cleaned_line.split('|')] score_map[student_id] = score # 第二步:读取student.txt,构建学生ID到姓名的字典 student_info_map = {} with open('student.txt', 'r', encoding='utf-8') as student_file: for line in student_file: cleaned_line = line.strip() if not cleaned_line: continue # 分割ID、名字、姓氏,处理空格和大小写 id_part, first_name, last_name = [part.strip() for part in cleaned_line.split('|')] # 把姓氏转成小写,匹配输出要求的jones格式 student_info_map[id_part] = (first_name, last_name.lower()) # 第三步:生成指定格式的输出内容 output_parts = [] for student_id in student_info_map: # 只保留已提交作业的学生(即ID在成绩字典里的) if student_id in score_map: first_name, last_name = student_info_map[student_id] score = score_map[student_id] # 拼接成要求的格式:ID 名字,姓氏,成绩 output_parts.append(f"{student_id} {first_name},{last_name},{score}") # 把所有部分用空格连接,输出最终结果 print(' '.join(output_parts))
代码说明:
- 用
with open()语句读取文件,这样会自动关闭文件,避免资源泄漏。 - 构建字典是为了快速通过学生ID查找对应的成绩和姓名,效率比反复遍历列表高。
- 处理每个行的时候先去掉前后空格和空行,避免因为文件里的多余空格导致出错。
- 把姓氏转成小写,是为了匹配题目输出里的
jones(原文件是Jones)。 - 最后把所有符合条件的学生信息拼接成一行,用空格分隔,就得到了你要的输出。
内容的提问来源于stack exchange,提问作者Manan Prajapati
相关产品推荐
相关产品推荐

