繁体   English   中英

自动将字典中的列表项附加到默认值python

[英]Auto append list items in dictionary with default values python

我正在尝试创建一个出勤记录器,在其中创建一本字典,其中填充了学生姓名。 这些名字将是列出我要附加他们的课堂出勤数据的列表(无论他们是否参加过课堂)。 我到目前为止的代码显示在下面`

#! /bin/python3
#add student to dict
def add_student(_dict):
    student=input('Add student :')
    _dict[student]=[]
    return _dict

#collect outcomes
def collector(student,_dict, outcome):
    _dict[student].append(outcome)
    return _dict

#counts target
def count(_dict,target):
    for i in _dict: 
        # records total attendance names
        attendance_stat = len(_dict[i])
        # records total instances absent
        freq_of_absence=_dict[i].count(target)
        # records percentage of absence
        perc_absence = float((freq_of_absence/attendance_stat)*100)
        print(i,'DAYS ABSENT =',freq_of_absence)
        print('TOTAL DAYS: ', i, attendance_stat)
        print('PERCENTAGE OF ABSENCE:', i, str(round(perc_absence, 2))+'%')

#main function
def main():
    #date=input('DATE: ')
    outcomes=['Y','N']
    student_names = {}
    try:
        totalstudents = int(input('NO. OF STUDENTS: '))
    except ValueError:
        print('input an integer')
        totalstudents = int(input('NO. OF STUDENTS: '))
    while len(student_names) < totalstudents:
        add_student(student_names)
    print(student_names)
    i = 0
    while i < totalstudents:
        i = i + 1
        target='Y'
        student=str(input('student :'))
        outcome=str(input('outcome :'))
        collector(student,student_names,outcome)
    count(student_names,target)

if __name__=='__main__':
    main()

`该代码到目前为止运行良好,但问题是当学生人数过多时,投入的时间大大减少了上课时间。 由于缺席人数通常少于在场人数,因此有可能从字典中选择缺席学生,该缺席学生将为每个所选缺席添加值Y,同时将N附加到字典中的其余列表。

这并不是您所要的,但我认为会有所帮助。 为何不要求用户在第二部分中每次都输入一个名称,为什么不只自己打印名称,而只问结果呢? 您的最后一个while循环将变为for循环,如下所示:

for student_name in student_names:
    outcome = input("Outcome for {}: ".format(sudent_name))
    collector(student_name, student_names, outcome)

您还可以添加一些逻辑以检查结果是否为空字符串,如果是,则将其设置为“ N”。 这将只允许您按Enter键输入大多数名称,而只需要为某些不存在的名称键入“ Y”。 看起来像这样:

for student_name in student_names:
    outcome = input("Outcome for {}: ".format(sudent_name))
    if outcome = "":
        outcome = "N"
    collector(student_name, student_names, outcome)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM