2016-02-11 16 views
0

我是想圖paths格式化存儲爲嵌套表爲什麼我的其他列表從第一次名單

一個系列的所有可能的路徑複製後修改最初我寫了一個解決方案有兩個for循環的話,我當我遇到這個問題時,決定把它變成單一的列表理解。我的第二個列表comper不斷得到上運行,即使我從comp

複製它,我連打印出來的ID和比較的對象修改,蟒蛇說,他們沒有引用同一個對象,但是當我進行任何操作compcomper也受到影響。

據我所知,python列表是通過引用傳遞的,所以如果你想要一個新的新副本來處理它們,那麼它們必須被複制,但爲什麼會發生這種情況呢?,我不認爲這是一個錯誤,因爲我已經複製列出了這麼多次沒有這種行爲

paths = { 
     'A': ['B', 'C'], 
     'B': ['D'], 
     'C': ['E'] 
     } 

comp = [[key, i] for key in sorted(paths, key = None) for i in paths.get(key) if isinstance(paths.get(key), list)] 
print(comp, 'this is the original comp') 

comper = comp[:] # tried to copy the contents of comp into comper even tried list(comp), still get the same result 
print(comper, 'comper copied, is unchanged') 

if comp is comper: 
    print('yes') 
else: 
    print(id(comp), id(comper)) 

for count, ele in enumerate(comp): 
    for other in comp: 
     if ele[-1] == other[0]: 
      comp[count].append(other[-1]) 
      comp.remove(other) 
      # comper.remove(other) fixes the problem but why is comper getting modified even when id's are different  

print(comper, 'apparently comper has changed because the operation was carried out on both') 
print(comp) 

print(id(comp), id(comper)) 

這是輸出我得到

[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] this is the original comp 
[['A', 'B'], ['A', 'C'], ['B', 'D'], ['C', 'E']] comper copied, is unchanged 
139810664953992 139810664953288 
[['A', 'B', 'D'], ['A', 'C', 'E'], ['B', 'D'], ['C', 'E']] apparently comper has changed because the operation was carried out on both 
[['A', 'B', 'D'], ['A', 'C', 'E']] 
139810664953992 139810664953288 

康珀有多餘的元素,因爲他們沒有從列表中刪除,如果我去掉,消除其他行從comper列表,然後我基本上得到相同的導致

我連打印出的ID在底部,他們仍然不同

+0

進口複印件; comper = copy.copy(comp); – Prune

+0

@Prune試過它沒有工作.... comper仍在修改中 – danidee

+0

因爲你正在處理嵌套列表,所以你需要'deepcopy'。 – Blckknght

回答

0
Import copy 
Comper = copy.deepcopy(comp) 
相關問題