首页 > 解决方案 > 如何解决可能由 list.append() 引起的副作用?

问题描述

我正在编写一个程序,要求用户输入学生信息。到字典,并附加每个学生的信息。列表如下。但结果表明,所有先前附加的数据都被最后一个数据重载了。

我无法弄清楚列表中的内部操作是如何工作的。是什么因素导致之前的数据过载?

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'}

标签: python

解决方案


  • student每次调用该函数时都会覆盖。在每个循环中,您每次都附加相同的实例。
  • 只是看看这个例子。
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


推荐阅读