python - 如何解决可能由 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'}
解决方案
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
推荐阅读
- c++ - 整数到浮点转换何时无损?
- php - 使用 PHP 生成带图像的 word 文档
- automation - EarlGrey 可以用作只有 ipa 文件的测试工具吗?
- reactjs - Reactjs:无法使用“npm start”启动开发服务器
- r - 使用 Quanteda 清理语料库
- electron - 我的 spectron app.client 不包含所有方法
- javascript - 尝试运行 Node.js 应用程序时如何修复“语法错误:无效或意外令牌”
- r - 将 case_when 和 between 与对应阈值表一起使用
- html - 弹性项目中的锚标记尊重所有填充,没有 display:inline-block 属性的边距。这是为什么?
- python - 将结果从并行计算移动到 Python 中的最终数组