gpt4 book ai didi

python - 如何使用字典为每个学生存储多个条目

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:07 25 4
gpt4 key购买 nike

这里是问题陈述:

有'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 的新手,如果有人能帮助我,我会很高兴。

最佳答案

实际上,您需要创建一个嵌套字典,其中名称作为值,另一个字典作为键,嵌套字典可能看起来像这样:

{
'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"

关于python - 如何使用字典为每个学生存储多个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30360964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com