【问题标题】:What is going on with this array assignment?这个数组赋值是怎么回事?
【发布时间】:2014-11-08 06:30:07
【问题描述】:

我一直在尝试用 Python 制作一个基于终端的扫雷克隆。这是我生成雷区的函数:

BOMB = '#' # The symbol for the bomb
def generateField(width, height, bombs):
    field = [[0] * height] * width # Make the empty array grid
    for bomb in range(0, bombs):
        x, y = random.randint(0, width - 1), random.randint(0, height - 1)
        print((x, y)) # For debugging, remove later
        field[x][y] = BOMB #
    return field

还没有完成。 但是,当我为宽度为 12、高度为 12、宽度为 12 的炸弹调用 generateField(12, 12, 12) 时,它给了我这样的信息:

[
    [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, '#', '#', '#']
]

有人能给我解释一下发生了什么,或者出了什么问题吗?

【问题讨论】:

标签: python arrays for-loop


【解决方案1】:

这部分造成了麻烦:

field = [[0] * height] * width

试试这个:

field = [[0] * height for _ in xrange(width)]

说明:您将 相同 引用复制到列表中的单个子列表,因此对一个元素所做的任何更改都将反映在“其他”上 - 因为实际上,只有一个单个被多次引用的子列表。

我提出的解决方案负责每次创建不同的子列表(使用列表理解),因此不会共享子列表引用。这是 Python 中一个相当常见的问题,请查看post 了解更多详细信息。

【讨论】:

  • 啊,我现在明白了。非常感谢,它现在提供了正确的输出!
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 2011-06-28
  • 2020-04-03
  • 2018-06-20
  • 2011-08-25
  • 1970-01-01
相关资源
最近更新 更多