二维列表错误地在python中分配值 [英] Two-dimensional list wrongly assigning values in python

查看:108
本文介绍了二维列表错误地在python中分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Board:

    def __init__(self):
        self.board = self.createBoard()

    def createBoard(self):
        line = []
        for i in range(7):
            line.append(' ')
        board = []
        for i in range(7):
            board.append(line)
        return board

    def showBoard(self):
        line = "| "
        for x in range(len(self.board)):
            for y in range(len(self.board)):
                line += self.board[x][y] + " | "
            print("-" * 29)
            print(line)
            line = "| "
        print("-" * 29)

if __name__ == '__main__':
    board = Board()
    board.showBoard()
    board.board[1][1] = "O"
    board.showBoard()

当我陷入这个非常奇怪的问题时,我正在研究一个connect-4 python控制台演示/游戏.

I was working on a connect-4 python console demo/game when I got stuck on this really weird issue.

上面的代码输出如下:

-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------

奇怪的是,我从未将O分配给所有这些位置,我仅将其分配给了位置[1] [1].

The weird thing is, I never assigned O to all those positions, I only assigned it to the position [1][1].

我期望输出为:

-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------
|   | O |   |   |   |   |   | 
-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------
|   |   |   |   |   |   |   | 
-----------------------------

我极有可能遗漏了一些明显的小东西,但经过一个多小时的尝试,我真的找不到问题了.

It is extremely likely that I'm missing something obvious and small but I've been looking and trying for over an hour and I really can't find the problem.

这不像我的board.board列表比其他任何二维列表都更奇怪.

It's not like my board.board list is any more odd than any other two-dimensional list.

[[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']]

(这是我print(board.board)时得到的东西)

(It's what I get when I print(board.board))

将其复制并粘贴到IDLE中,我得到以下信息:

Copying and pasting that into IDLE I get the following:

>>> a = [[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']]
>>> a[1][1] = "O"
[[' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', 'O', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ']]

哪个可以给我带来适当的董事会价值.

Which gets me the proper board value.

我的代码中明显有什么错,以至于我遗漏了什么?我很确定,当你们中的任何一个找到答案时,我都会羞愧地摇头,这很可能很糟糕.

What is so obviously wrong in my code that I'm missing it? I'm pretty sure that when any of you find an answer that I'll shake my head in shame, it's likely that bad.

足够的自我欺骗,为什么我的代码board.board[1][1] = "O"board.board中的每一行分配值"O"?

Enough self-shaming, so why does my code board.board[1][1] = "O" assign the value "O" to the every single row in board.board?

将第一个1更改为0到6之间的任何其他数字也不会更改任何内容.都是一样的.

Changing the first 1 to any other number from 0-6 doesn't change anything either. It's all the same.

推荐答案

常见问题解答中的问题出在代码的这一部分:

The problem is in this part of the code:

board = []
for i in range(7):
    board.append(line)

您正在创建一个列表,其中包含对同一列表line的7个引用.因此,当您修改一个时,其他所有都将更改,因为它们是相同的列表.

You're creating a list with 7 references to the same list, line. So, when you modify one, the others all change, because they're the same list.

解决方案是创建7个单独的列表,如下所示:

The solution is to create 7 separate lists, like this:

def createBoard(self):
    board = []
    for i in range(7):
        line = []
        for i in range(7):
            line.append(' ')
        board.append(line)
    return board

或更简单地说,是原始列表的单独副本:

Or, more simply, make separate copies of the original list:

def createBoard(self):
    line = []
    for i in range(7):
        line.append(' ')
    board = []
    for i in range(7):
        board.append(line[:])
    return board


在使用此功能时,您可以使用列表推导功能大大简化此操作:


While we're at it, you could simplify this tremendously by using list comprehensions:

def createBoard(self):
    return [[' ' for j in range(7)] for i in range(7)]


或者,如常见问题解答所建议,您最好使用更智能的多维数组对象,例如numpy或pandas提供的对象:


Or, as the FAQ suggests, you might do better to use a smarter multidimensional array object, like the ones numpy or pandas provide:

def createBoard(self):
    return np.tile(' ', (7, 7))

缺点是您将需要安装numpy,因为标准库中没有像这样工作的东西.但是优点是您拥有用于处理数组的强大工具-a[1, 1]并不比a[1][1]容易得多,但是a[:,1]来访问第二列要比[row[1] for row in a]容易得多.

The disadvantage is that you will need to install numpy, because there's nothing in the standard library that works like this. But the advantage is that you have powerful tools for dealing with arrays—a[1, 1] isn't much simpler than a[1][1], but a[:,1] to access the second column is a lot simpler than [row[1] for row in a].

这篇关于二维列表错误地在python中分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆