【发布时间】: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