def gen_stu():
students_names=['venkatesh','kiran','ravi'] # assigning the names of students
student_marks=[]
student_names_marks={}
for i in students_names:
for m in range(1,3): # asking user for marks for respective students
student_names_marks[i]=int(input(f'enter the marks of {i} for subject {m}: '))
student_marks.append(student_names_marks[i])
student_names_marks[i]=student_marks
return student_names_marks
print(gen_stu())
输出如下:
enter the marks of venkatesh for subject 1: 1
enter the marks of venkatesh for subject 2: 2
enter the marks of kiran for subject 1: 3
enter the marks of kiran for subject 2: 4
enter the marks of ravi for subject 1: 5
enter the marks of ravi for subject 2: 6
我得到的输出为:
{'venkatesh': [1, 2, 3, 4, 5, 6], 'kiran': [1, 2, 3, 4, 5, 6], 'ravi': [1, 2, 3, 4, 5, 6]}
但我需要输出为:
{'venkatesh': [1, 2], 'kiran': [3, 4], 'ravi': [5, 6]}
采用 dict.setdefault
例如:
def gen_stu():
students_names=['venkatesh','kiran','ravi'] # assigning the names of students
student_names_marks={}
for i in students_names:
for m in range(1,3): # asking user for marks for respective students
student_names_marks.setdefault(i, []).append(int(input(f'enter the marks of {i} for subject {m}: ')))
return student_names_marks
print(gen_stu())
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句