这是问题说明:
有一个’n’个学生的记录,每个记录都有学生的姓名,在数学,物理和化学中获得的百分比分数.用户输入整数“ n”,后跟“ n”个学生的姓名和标记.我需要将记录保存为字典数据类型.然后,用户输入一个学生的姓名,并且您需要打印该学生获得的平均百分比标记,并校正到两位小数位.
到目前为止我尝试过的是:
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['studentname', 'mathmarks', 'physicsmarks', 'chemistrymarks']
for i in range(0,num_students):
for entry in student_data:
student_info[entry] = raw_input(entry )
print student_info
print"please enter student name"
name = raw_input("student name")
if student_info['studentname'] == name:
print "Average student marks:", (int(student_info['mathmarks']) + int(student_info['physicsmarks']) + int(student_info['chemistrymarks']))/3
else:
print"please enter valid name"
该代码在num_students = 1的情况下起作用,但是,如果num_students> 1,则代码失败.
我无法在字典中保存每个学生的条目.
我是python的新手,如果有人可以帮助我,我会很高兴.
解决方法:
实际上,您需要创建一个嵌套的字典,其名称作为值,另一个dict作为键,以类似的方式,嵌套的dict可能看起来像:
{
'anmol': {'chemistrymarks': 3, 'physicsmarks': 2, 'mathmarks': 1},
'uppal': {'chemistrymarks': 6, 'physicsmarks': 5, 'mathmarks': 4}
}
因此,您需要添加以下行来创建嵌套字典.
num_students = int(raw_input("Please enter number of students:"))
print "you entered %s students" %num_students
student_info = {}
student_data = ['Math marks : ', 'Physics marks : ', 'Chemistry marks : ']
for i in range(0,num_students):
student_name = raw_input("Name :")
student_info[student_name] = {}
for entry in student_data:
student_info[student_name][entry] = int(raw_input(entry)) #storing the marks entered as integers to perform arithmetic operations later on.
#print student_info
print"Please enter student name ?"
name = raw_input("Student name : ")
if name in student_info.keys():
print "Average student marks : ", str(sum(student_info[name].values())/3.0)
else:
print"please enter valid name"