0

我正在尝试重用字典中的向量,但即使我拉出向量并重命名它,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]

4

2 回答 2

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'],您会得到更改后的向量而不是原始向量。

PS -lst[:]进行浅拷贝,copy.deepcopy(lst)用于深拷贝列表。

于 2013-10-30T13:38:29.010 回答
1

当您将列表分配给变量vector时,您实际上并没有复制列表,您只是获得对它的引用。如果你想要一个副本,你必须使用例如 slice-operator 显式复制它:

vector = d['id 2'][:]
于 2013-10-30T13:43:06.367 回答