2013-10-30 17 views
0

我想重新使用字典中的矢量,但是Python修改字典,即使我拉動矢量並重新命名它。圍繞這個問題的任何想法。這裏是我的代碼:如何在Python中重新使用字典中的矢量?

# Set up dictionary 

d = {'id 1':[20,15,30]} 
d['id 2'] = [5,10,50] 

# Pull a vector from the dictionary and decrease the first entry in the vector 

vector = d['id 2'] 
vector[0] = vector[0] - 1 
print vector 

# Pull the same vector from the dictionary (This is where I want the original vector) 

vector2 = d['id 2'] 
vector2[0] = vector2[0] - 1 
print vector2 

當我

print vector 
# => [4, 10, 50] 

當我

print vector2 
# => [3, 10, 50] 

爲什麼它不重新分配vector2原來的[5,10,50]vector?我希望這兩個給我[4,10,50],但第二個給我[3,10,50]

回答

2

製作列表的副本或深層副本。

In [34]: d = {'id 1':[20,15,30]} 

In [35]: d['id 2'] = [5,10,50] 

In [36]: vector = d['id 2'][:] 

In [37]: vector[0] = vector[0] - 1 

In [38]: print vector 
[4, 10, 50] 

In [39]: vector2 = d['id 2'][:] 

In [40]: vector2[0] = vector2[0] - 1 

In [41]: print vector2 
[4, 10, 50] 

列表是可變的,所以當你開始做vector[0] = vector[0] - 1,你改變的地方列表(如vector2 = d['id 2']獲取到原始列表的引用),所以當你vector2 = d['id 2'],你會得到改變的載體,而不是原來的一個。

P.S - lst[:]生成淺拷貝,使用copy.deepcopy(lst)深拷貝列表。

+0

這樣一個簡單的解決方案。非常感謝。 – myname

+0

不客氣。隨時接受答案。 :) –

1

當您將列表分配給變量vector時,您實際上並未複製列表,只能獲取對該列表的引用。如果你想要一份副本,你必須使用例如片運算符:

vector = d['id 2'][:]