有人可以在下面的代码中告诉我,如何防止" Cvalue"附加到" fred"当我只想将它附加到结果[键]?
我使用的是python 2.7,但python 3的行为相同。
#!/usr/bin/env python
hdict = {52951331: [5], 23396132: [4], 82982473: [19, 37], 126988879: [20] }
Cdict = {23396132: [19, 37], 82982473: [4], 126988879: [5], 52951331: [20]}
result = {}
for key, value in hdict.iteritems():
if key in Cdict:
result[key] = value
for Cvalue in Cdict[key]:
fred = value
print 'fred1: ', fred
result[key].append(Cvalue)
print 'fred2: ', fred
答案 0 :(得分:0)
为什么不尝试使用副本。
#!/usr/bin/env python
import copy
hdict = {52951331: [5], 23396132: [4], 82982473: [19, 37], 126988879: [20]}
Cdict = {23396132: [19, 37], 82982473: [4], 126988879: [5], 52951331: [20]}
result = {}
for key, value in hdict.iteritems():
if key in Cdict:
result[key] = value
for Cvalue in Cdict[key]:
fred = copy.copy(value)
print 'fred1: ', fred
value.append(Cvalue)
print 'fred2: %s, value: %s' % (fred, value)