【问题标题】:Auto append list items in dictionary with default values python使用默认值python在字典中自动附加列表项
【发布时间】:2017-04-08 00:04:45
【问题描述】:

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

#! /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 附加到字典中的剩余列表。

【问题讨论】:

    标签: python list python-3.x dictionary default-value


    【解决方案1】:

    这并不完全符合您的要求,但我认为它会有所帮助。与其要求用户每次都为第二部分输入一个名字,为什么不自己打印名字,只询问结果呢?您的最后一个 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)
    

    【讨论】:

    • 非常感谢,非常感谢。我现在可以跟踪我的学生并确保没有人掉队。
    • 不客气。如果对您有帮助,您介意将其标记为解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 2023-02-02
    • 2019-11-07
    • 2019-03-29
    • 2012-05-25
    • 2016-01-16
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多