[英]How do I stop my function from entering a value into every list?
For my assignment, I need to insert a value into a particular index in a sublist of a list which contains 3 lists.对于我的分配,我需要在包含 3 个列表的列表的子列表中的特定索引中插入一个值。 Instead of changing the value in only 1 sublist, it changes it in every sublist.它不是仅更改 1 个子列表中的值,而是在每个子列表中更改它。
I have tried reentering the values which are used to determine the indices.我尝试重新输入用于确定索引的值。
def make_move(cur, move, player):
m0 = move[0]
m1 = move[1]
cur[m0][m1] = player
make_move(world, (1,0), 'X')
print(world)
I expect the output to be:我希望 output 是:
[['', '', ''], ['X', '', ''], ['', '', '']]
What I am receiving is:我收到的是:
[['X', '', ''], ['X', '', ''], ['X', '', '']]
I made the world function as follows:我做了世界function如下:
def set_up_game(size):
n = 0
num = 0
s = int(get_game_size(size))
game = []
rows = []
columns = ''
while n < s:
rows.append(columns)
n += 1
while num < s:
game.append(rows)
num += 1
return game
The problem is the line:问题是这条线:
game.append(rows)
Change it to:将其更改为:
game.append(list(rows))
Which will create new lists within the game
list.这将在game
列表中创建新列表。
What you did initially (with the while loop) is equivalent to:您最初所做的(使用 while 循环)相当于:
game = [row] * num
You can see the problem with doing that here .你可以在这里看到这样做的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.