您将在 for 循环中使用的 student 变量中获得学生姓名。然后,要访问学生的值,您必须使用带键的字典来获取它。
例如:
如果您打印变量 students_dict_comp,它将如下所示:
{'彼得': [24, 3.1], '玛丽': [25, 3.8], '乔治': [22, 2.5], '艾玛': [20, 2.0] }
现在,要访问 Mary 的信息,您必须编写:
students_dict_comp['Mary'] # [25, 3.8]
# or if we use another variable to save name
student = 'Mary'
student_info = students_dict_comp[student] # [25, 3.8]
如果我们打印它,我们将得到一个 [25, 3.8] 的列表。现在,如果我们想获取他的年龄或 CGPA,我们可以像下面这样得到它:
marry_info = students_dict_comp['Mary'] # [25, 3.8]
marry_age = marry_info[0]
marry_cgpa = marry_info[1]
# or we can directly access
mary_age = students_dict_comp['Mary'][0] # age in 0th position
mary_cgpa = students_dict_comp['Mary'][1] # cgpa in 1th position
在 for 循环中,我们在 student 变量中获得了每个学生的姓名。所以,如果我们想访问他们的名字,我们可以使用 student 变量。否则,如果我们想访问学生年龄或 cgpa,那么我们可以像这样从 dict 访问:
student_gpa = students_dict_comp[student][1]
#another way
student_info = students_dict_comp[student] # an array with two value
student_gpa = student_info[1] # cgpa in 1 no. position.
students_dict_comp[student] 将给学生信息,这是一个包含两个值的数组。然后,要获得 CGPA,我们必须访问 1 号。位置。
之后,如果我们打印学生变量,我们将得到学生姓名。
带有解决方案的完整代码将是:
students = ["Peter", "Mary", "George", "Emma"]
student_ages = [24, 25, 22, 20]
student_gpa = [3.1, 3.8, 2.5, 2.0]
student_fail = 3.0
students_dict_comp = {name:[age,gpa] for name, age, gpa in zip(students, student_ages, student_gpa)}
print(students_dict_comp)
def students_failed (students_dict_comp):
for student in students_dict_comp:
# print(student) # Peter, Mary, George, Emma
student_gpa = students_dict_comp[student][1]
if student_gpa >= student_fail:
print(student, " passed")
else:
print(student, " failed")
students_failed(students_dict_comp)