我寫了下面一段代碼:
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)])
