我写了下面一段代码:
1 students = [] #定义一个students列表 2 stu_id = 1 3 score = 100 4 for num in range(1,7): #列表中的元素是字典结构 5 new_student = { 6 'stu_id':stu_id, 7 'score':score 8 } 9 students.append(new_student) 10 stu_id = stu_id + num 11 score = 100 - num* 2 12 print("--------print students information-------") 13 for std in students: 14 print(std.items()) 15 16 '''定义 teached_students 列表,是student列表的子集''' 17 teached_students = students[-4:] 18 19 print("\n--------print teached_students information-------") 20 for std in teached_students: 21 print(std.items()) 22 23 '''修改 students[-3] and 删除 students[-1]''' 24 students[-3]['score'] = 59 25 del students[-1] 26 students.append({'stu_id':99, 'score':120}) 27 28 print("\n----------After modify students[-3] and delelet students[-1]-------") 29 print("\n--------print teached_students information-------") 30 print("\t---------why does the \"teached_students[-3]\" changed, \n" + 31 "\t---------but \"teached_students[-1]\" haven't been removed?---------") 32 for std in teached_students: 33 print(std.items()) 34 print("\n--------print students information-------") 35 for std in students: 36 print(std.items())
一、建立了一个students列表,列表元素是包含2个键的字典。
二、建立了一个teached_students列表,他是对students列表的一个截取,即他的子集。
三、修改学生列表中一个元素,删除一个元素。(选取的这两个元素都包含在teached_students列表中)
四、发现问题:修改student列表中元素value时,为什么teached_students列表中的元素value也变了?
难道这是说对于字典列表元素的复制,并没有真正的分配内存空间,而是仅仅做了一个索引?
但若是如此,为什么删除students列表中的元素时,teached_students列表中的元素没有同时被删除呢?
运行结果如下:
--------print students information-------
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)]) #删除此元素
--------print teached_students information-------
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)])
----------After modify students[-3] and delelet students[-1]-------
--------print teached_students information-------
---------why does the "teached_students[-3]" changed,
---------but "teached_students[-1]" haven't been removed?---------
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)]) #为什么此元素没被删除?!!!
--------print students information-------
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)])