[英]Why does the original list change when I change the copied list (PYTHON)
[英]Python: why my original list is affected after updating copied list
twoSeq=[['28.406925,77.285590', '28.409969,77.292279'],
['28.406925,77.285590', '28.402476,77.292956'],
['28.409969,77.292279', '28.403020,77.298851'],
['28.403020,77.298851', '28.392363,77.306091'],
['28.392363,77.306091', '28.378515,77.313990'],
['28.378515,77.313990', '28.367469,77.315308'],
['28.402476,77.292956', '28.399600,77.297313'],
['28.402476,77.292956', '28.397301,77.294096'],
['28.399600,77.297313', '28.392247,77.301909'],
['28.392247,77.301909', '28.392363,77.306091'],
['28.397301,77.294096', '28.399600,77.297313']]
def N_Seq(twoSeq):
first=twoSeq.copy()
last=twoSeq.copy()
for i in range(len(first)):
first[i].pop(0)
print(first,"--------")
for j in range(len(last)):
last[j].pop()
print(first)
N_Seq(twoSeq)
輸出:
[['28.409969,77.292279'], ['28.402476,77.292956'], ['28.403020,77.298851'], ['28.392363,77.306091'], ['28.378515,77.313990'], ['28.367469,77.315308'], ['28.399600,77.297313'], ['28.397301,77.294096'], ['28.392247,77.301909'], ['28.392363,77.306091'], ['28.399600,77.297313']] --------
[[], [], [], [], [], [], [], [], [], [], []]
list.copy
創建列表的淺拷貝。 這意味着它會創建一個新列表並將對項目的引用插入其中。 在這種情況下,您應該使用copy.deepcopy
,它返回一個深層副本。
從文檔:
淺拷貝和深拷貝的區別僅與復合對象(包含其他對象的對象,如列表或類實例)有關:
淺拷貝構造一個新的復合對象,然后(在可能的范圍內)向其中插入對原始對象中的對象的引用。
深拷貝構造一個新的復合對象,然后遞歸地將原始對象中的對象的副本插入其中。
淺表副本
淺拷貝僅復制列表本身,它是對列表中對象的引用的容器。 如果包含自己的對象是可變的,並且其中一個被更改,則更改將反映在兩個列表中。
深拷貝
深復制列表與原始列表完全不同。
import copy
new_list = copy.deepcopy(old_list)
供參考。
import copy
twoSeq=[['28.406925,77.285590', '28.409969,77.292279'],
['28.406925,77.285590', '28.402476,77.292956'],
['28.409969,77.292279', '28.403020,77.298851'],
['28.403020,77.298851', '28.392363,77.306091'],
['28.392363,77.306091', '28.378515,77.313990'],
['28.378515,77.313990', '28.367469,77.315308'],
['28.402476,77.292956', '28.399600,77.297313'],
['28.402476,77.292956', '28.397301,77.294096'],
['28.399600,77.297313', '28.392247,77.301909'],
['28.392247,77.301909', '28.392363,77.306091'],
['28.397301,77.294096', '28.399600,77.297313']]
def N_Seq(twoSeq):
first=copy.deepcopy(twoSeq)
last=copy.deepcopy(twoSeq)
for i in range(len(first)):
first[i].pop(0)
print(first,"--------")
for j in range(len(last)):
last[j].pop()
print(first)
N_Seq(twoSeq)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.