我正在编写一个程序,要求用户输入学生的信息。在字典里,并附上每个学生的信息。列表如下所示。但结果表明,前面的所有数据都是被最后一个数据重载的。
我不知道名单上的内部操作是怎么运作的。是什么因素导致先前的数据被重载?
student = {"first_name": 0,"last_name": 0,"matriculation_number": 0,
"course": 0,"university": 0}
student_list = []
def inputStudentData(num):
dict = student
for key in dict.keys():
msg = "Enter no." + str(num) +" student's " + key + ": "
data = input(msg)
dict[key] = data
return dict
def printStudentData(a):
for i in a:
print(i)
N = int(input("Enter numbers of students: "))
for i in range(1,N+1):
student_list.append(inputStudentData(i))
printStudentData(student_list)
结果是:
Enter numbers of students: 2
Enter no.1 student's first_name: 11
Enter no.1 student's last_name: 1
Enter no.1 student's matriculation_number: 1
Enter no.1 student's course: 1
Enter no.1 student's university: 1
Enter no.2 student's first_name: 2
Enter no.2 student's last_name: 2
Enter no.2 student's matriculation_number: 2
Enter no.2 student's course: 2
Enter no.2 student's university: 2
{'first_name': '2', 'last_name': '2', 'matriculation_number': '2', 'course': '2', 'university': '2'}
{'first_name': '2', 'last_name': '2', 'matriculation_number': '2', 'course': '2', 'university': '2'}
发布于 2019-10-30 21:14:17
每次调用函数时都要覆盖
l = []
d = {'a':0,'b':1}
l.append(d)
d['a'] = 100
l.append(d)
d['b'] = 200
l.append(d)
print(l)
输出:
[{'a': 100, 'b': 200}, {'a': 100, 'b': 200}, {'a': 100, 'b': 200}]
copy
或声明字典。PS:请不要使用关键字作为变量名。你会遇到晚上困扰你的问题。:D
发布于 2019-10-30 21:09:43
您需要使用dict = student.copy()
获得所需的输出
为什么这个节目是这样的?
因为您已经创建了一个全局字典学生,并且在每个循环中调用该函数并提供输入时,该函数接受全局dict学生并向其添加值,并且在list.append引用中添加了这个dict对象。
在第二个循环中,当您添加新数据时,这个全局dict被更新,对这个dict对象的引用被添加到列表中。
因此,在打印列表时,在打印函数中,当列表中的迭代器到达要打印的元素时,元素指向学生字典内存位置的值,而现在在学生内存位置的值是最后一个循环的值。因此,对于每个元素,使用相同的dict对象,并对每个循环进行更新,其引用存储在list中。因为每个元素都有相同的dict对象,并且引用相同的mem位置,所以所有的值都是相同的。
如何解决这个问题?
您需要创建字典对象的浅拷贝或深副本。
https://stackoverflow.com/questions/58633612
复制相似问题