cell={'num':0,'state':1}
cell_2d=[]
cell_list=[]
for i in range(2):
for j in range(2):
cell_list=cell_list+[cell]
cell_2d=cell_2d+[cell_list]
cell_list=[]
print "initially:"
print cell_2d
cell_2d[0][0]['num']=-1
print 开发者_高级运维"finally:"
print cell_2d
Output obtained is:
initially: [[{'state': 1, 'num': 0}, {'state': 1, 'num': 0}], [{'state': 1, 'num': 0}, {'state': 1, 'num': 0}]] finally: [[{'state': 1, 'num': -1}, {'state': 1, 'num': -1}], [{'state': 1, 'num': -1}, {'state': 1, 'num': -1}]]
when the line 11 is executed, I expect only the first element of the first list of cell_2d to be changed. But the output shows that all 'num' of all elements of cell_2d is changed to -1. Not able to get why this is happening. Can someone please tell me what is the mistake with the code? Thanx in advance.
OK, I see it. You're reusing the cell
object. Because Python uses references, you're just making four references to the same object, so when you change one, you change them all.
Inside your inner loop, try:
cell_list = cell_list + [{'num':1, 'state':0}]
Which can be shortened to:
cell_list.append({'num':1, 'state':0})
Or, in fact, you can replace the inner loop (with j) with:
cell_list = [{'num':1, 'state':0} for j in range(2)]
Simply replace this line
cell_2d=cell_2d+[cell_list]
With this
cell_2d = cell_2d + [ cell_list.copy() ]
This way python will make a copy from the dictionary 'cell_list' instead of storing a reference.
精彩评论