python第四章课后习题(6)

从资源文件中,获取fiel_list【namelist.csv】文件,该文件是所有同学的名单列表。与fiel_student【student.txt】文件进行对比,按学号顺序列出缺席同学的学号和姓名(在fiel_list【namelist.csv】文件中,但不在fiel_student【student.txt】中)。

例如:
1907040115 张三
1907040220 李四
提示:对于两个数据集的比较,建议使用set数据类型

def fun6(file_student='student.txt',file_list='namelist.csv'):
    """
    Compare "namelist.csv" with "student.txt" to list the absent student's Student ID and name in order of Student ID.
    return a string; e.g. "1907040115 张三\n1907040220 李四"
    """
    with open(f'{path}/{file_student}','r',encoding='utf8') as f:
        l=f.readlines()
        s1=set('1')
        for i in range(len(l)):
            name=l[i].split()[1]
            num=l[i].split()[2]
            s1.add(f'{num} {name}')
    with open(abspath(file_list),'r',encoding='utf8') as f1:
        s2=set('1')
        lst=f1.read().splitlines()
        for i in range(1,len(lst)):
            s2.add(lst[i].replace(',',' '))
    diff=list(s2-s1)
    res='\n'.join(diff)
    return res

猜你喜欢

转载自blog.csdn.net/qq_53029299/article/details/114598325