简体   繁体   English

如何阻止我的 function 在每个列表中输入值?

[英]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.

相关问题 如何在 function 的每个循环之后停止重新定义变量? - How do I stop redefining a variable after every loop of a function? 如何创建字典,其中每个键都是列表中的一个值,而每个值都是列表中除键之外的所有值 - How do I create a dictionary where every key is a value from a list, and every value is all the values from the list except the key 有唯一列表时如何停止该功能? - How do I stop the function when I have a unique list? 如何根据列表中的元素数量停止迭代? - How do I stop iterating based on the number of elements on my list? 每次我使用 speakRemember() function 时,如何停止运行 remember() function 的代码? - How do I stop the code running the remember() function every time I use speakRemember() function? 提供BMI值时,如何阻止BMI计算器添加不需要的“无”? - How do I stop my BMI calculator from adding an unwanted “None” when giving the BMI value? 我如何从列表中表示一个字典,假设它旁边的其他所有数字都是它的值? - How do I represent a dictionary from a list assuming that every other number by its side is its value? 如何获取我的列表以打印出每一行? - How do I get my list to print out every line? 如何停止函数以遍历列表中的所有项目 - how do I stop a function to iterate through all items in a list 当我的暂停在pygame中播放我的game_loop函数时,如何阻止我的游戏重启? - How do I stop my game from restarting when my pause plays my game_loop function in pygame?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM