我寫了下面一段代碼:
students = [] #定義一個students串列
stu_id = 1
score = 100
for num in range(1,7): #串列中的元素是字典結構
new_student = {
'stu_id':stu_id,
'score':score
}
students.append(new_student)
stu_id = stu_id + num
score = 100 - num* 2
print("--------print students information-------")
for std in students:
print(std.items())
'''定義 teached_students 串列,是student串列的子集'''
teached_students = students[-4:]
print("\n--------print teached_students information-------")
for std in teached_students:
print(std.items())
'''修改 students[-3] and 洗掉 students[-1]'''
students[-3]['score'] = 59
del students[-1]
students.append({'stu_id':99, 'score':120})
print("\n----------After modify students[-3] and delelet students[-1]-------")
print("\n--------print teached_students information-------")
print("\t---------why does the \"teached_students[-3]\" changed, \n" +
"\t---------but \"teached_students[-1]\" haven't been removed?---------")
for std in teached_students:
print(std.items())
print("\n--------print students information-------")
for std in students:
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)])
uj5u.com熱心網友回復:
我試過了,如果單獨使用串列,不會出現這個問題;但如果用字典串列,問題就出現了。求高手幫忙解答。。。轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/90870.html
上一篇:python中,關于檔案的讀取路徑中包含中文報錯的解決辦法
下一篇:從github下了一個專案,匯入到pycharm,但是點run的時候會出現這個提示,有沒有大神知道該怎么處理,萬分感激
