求助:关于python中字典列表嵌套使用的问题

[复制链接]
查看11 | 回复1 | 2021-1-27 06:35:01 | 显示全部楼层 |阅读模式
我写了下面一段代码:

students=[]#定义一个students列表
stu_id=1
score=100
fornuminrange(1,7):#列表中的元素是字典结构
new_student={
'stu_id':stu_id,
'score':score
}
students.append(new_student)
stu_id=stu_id+num
score=100-num*2
print("--------printstudentsinformation-------")
forstdinstudents:
print(std.items())
'''定义teached_students列表,是student列表的子集'''
teached_students=students[-4:]
print("\n--------printteached_studentsinformation-------")
forstdinteached_students:
print(std.items())
'''修改students[-3]and删除students[-1]'''
students[-3]['score']=59
delstudents[-1]
students.append({'stu_id':99,'score':120})
print("\n----------Aftermodifystudents[-3]anddeleletstudents[-1]-------")
print("\n--------printteached_studentsinformation-------")
print("\t---------whydoesthe\"teached_students[-3]\"changed,\n"+
"\t---------but\"teached_students[-1]\"haven'tbeenremoved?---------")
forstdinteached_students:
print(std.items())
print("\n--------printstudentsinformation-------")
forstdinstudents:
print(std.items())


一、建立了一个students列表,列表元素是包含2个键的字典。
二、建立了一个teached_students列表,他是对students列表的一个截取,即他的子集。
三、修改学生列表中一个元素,删除一个元素。(选取的这两个元素都包含在teached_students列表中)
四、发现问题:修改student列表中元素value时,为什么teached_students列表中的元素value也变了?
难道这是说对于字典列表元素的复制,并没有真正的分配内存空间,而是仅仅做了一个索引?
但若是如此,为什么删除students列表中的元素时,teached_students列表中的元素没有同时被删除呢?
运行结果如下:
--------printstudentsinformation-------
dict_items([('stu_id',1),('score',100)])
dict_items([('stu_id',2),('score',98)])
dict_items([('stu_id',4),('score',96)])
dict_items([('stu_id',7),('score',94)])#修改此元素的score值
dict_items([('stu_id',11),('score',92)])
dict_items([('stu_id',16),('score',90)])#删除此元素
--------printteached_studentsinformation-------
dict_items([('stu_id',4),('score',96)])
dict_items([('stu_id',7),('score',94)])
dict_items([('stu_id',11),('score',92)])
dict_items([('stu_id',16),('score',90)])
----------Aftermodifystudents[-3]anddeleletstudents[-1]-------
--------printteached_studentsinformation-------
---------whydoesthe"teached_students[-3]"changed,
---------but"teached_students[-1]"haven'tbeenremoved?---------
dict_items([('stu_id',4),('score',96)])
dict_items([('stu_id',7),('score',59)])#为什么此元素的score值变了?
dict_items([('stu_id',11),('score',92)])
dict_items([('stu_id',16),('score',90)])#为什么此元素没被删除?!!!
--------printstudentsinformation-------
dict_items([('stu_id',1),('score',100)])
dict_items([('stu_id',2),('score',98)])
dict_items([('stu_id',4),('score',96)])
dict_items([('stu_id',7),('score',59)])
dict_items([('stu_id',11),('score',92)])
dict_items([('stu_id',99),('score',120)])

分 -->
回复

使用道具 举报

千问 | 2021-1-27 06:35:01 | 显示全部楼层
我试过了,如果单独使用列表,不会出现这个问题;但如果用字典列表,问题就出现了。求高手帮忙解答。。。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行