问题
So I'm using a nested list to store some data and I'm having trouble with changing specific values of one of the sublists:
if attributes[3] == 'W':
self.board[3][3] = 'W'
(numbers are placeholders i'm using to test)
board is a class variable that is created as follows (I'm trying to create a grid as specified by a user, with their input for column and row sizes making up the first two parts of attributes)
self.board = []
rows = []
self.score = [0, 0]
for x in range(attributes[0]):
rows.append('')
for y in range(attributes[1]):
self.board.append(rows)
However, whenever I try to change the value of a sublist, it changes the values for all sublists for that same index:
[['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', '']]
I can't figure out what's wrong. Anyone have any ideas?
回答1:
I think the reason for this can be demonstrated on this very simple example:
a = [1,2,3]
b = [a,a,a] # <- this is what you are actually doing
print(list(map(id,b)))
#[140475353832712, 140475353832712, 140475353832712]
Please not that all ids are same above. This means that you are stroning in your list, references to the same object. thus changing one subsist, changes every sublist.
However, you should be doing this (or some equivalent):
b2 = [a[:], a[:], a[:]] #
print(list(map(id,b2)))
#[140475353832136, 140475353832072, 140475353832520]
Please note, different id for each sublist. Now b2 contains references to different sublists.
To sum up, you should have this:
for y in range(attributes[1]):
self.board.append(rows[:])
回答2:
By self.board.append(rows)
you are appending the same list in a loop. What you need is to append a copy of the rows list: self.board.append(rows[:])
So the modified code will be:
self.board = []
rows = []
self.score = [0, 0]
for x in range(attributes[0]):
rows.append('')
for y in range(attributes[1]):
self.board.append(rows[:])
来源:https://stackoverflow.com/questions/28825423/python-changing-values-of-a-nested-list