【问题标题】:Python - Construction of a two-dimensional list of random integers, shows repetition, that should not be there [duplicate]Python - 构建随机整数的二维列表,显示重复,不应该存在[重复]
【发布时间】:2020-02-14 13:08:31
【问题描述】:

我对 python 还很陌生,这是我遇到的第一个障碍。 这是正在发生的事情:

from random import randint

empty = [[0]*9]*9

def randomboard():
  board = empty
  for x in range(0,8):
    for y in range(0,8):
      nextInt = randint(0,29) - 20
      #nextInt = 0 if nextInt < 0 else nextInt
      board[x][y] = nextInt
  return board

def printboard(board):
  for x in range(0,8):
    print(board[x])
  print("----")

printboard(empty)
printboard(randomboard())

输出如下:

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 0, 0, 0, 0, 0, 0, 0, 0]


[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]

[3, -5, -5, -4, 7, -13, -15, -1, 0]


守则应该做什么: 创建一个空的 9x9 板。用随机值填充它。然后打印结果。

如您所见,第一个轴不断重复,尽管我觉得这不应该是这种情况,我只能尝试理解为什么会这样。 以下是几种可能性:

-RNG 种子在第一个循环的每次迭代后重置: 在这种情况下我什至不知道该怎么做,而且发生这种情况似乎非常不直观。

-我在构建随机列表的过程中做了一些奇怪的事情。可能是一些错误的语法,我已经从 java 中接管了: 我一直在研究其他代码示例,代码 sn-p 对我来说似乎仍然不错。也许我没有看到你看到的东西。

-printboard 函数只是一遍又一遍地打印第一行: 我已经尝试将函数替换为“print(board)”,但这也会返回重复列表。

-完全不同的东西,我一直在忽略

在这一点上,我非常感谢您的帮助。

提前谢谢你!

【问题讨论】:

  • 难以置信,是的!不过,我不小心点击了“不”,对不起。既然我有一个入口点,我将不得不对此进行更多研究。谢谢!

标签: python arrays list random


【解决方案1】:

我认为您正在对同一对象进行引用列表。看看这个帖子:Python initializing a list of lists

我对您的问题的解决方案看起来会有所不同。我不会从一个空列表开始,只需添加我需要的:

def randomboard():
    board = []
    for x in range(0,8):
        newline = []
            for y in range(0,8):
                newline.append(randint(0,29) - 20)
        board.append(newline)
    return board

【讨论】:

  • 你用这个@NougatNode 得到了你想要的结果?
猜你喜欢
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多