如何替换列表中列表中的元素(列表列表)?

时间:2017-01-10 05:09:49

标签: python list

我无法替换列表中列表中的元素。 我的代码是:

board_size = 2
number_of_squares_on_board = board_size * board_size


computers_places = []

while len(computers_places) < number_of_squares_on_board:

    placing = random.randint(0, number_of_squares_on_board-1)

    if placing not in computers_places:
        computers_places.append(placing)
        row = int(placing / board_size)
        column = int(placing % board_size)
        # print(computers_places)
        print("\nplacing: ", placing)
        print("col: ", column)
        print("row: ", row)

        column_list = board[column]
        column_list[row] = "[X]"

        print(board[column][row])
        print(board)
        print(computers_places)

输出如下:

placing:  1
col:  1
row:  0
[X]
[['[X]', '[ ]'], ['[X]', '[ ]']]
>>>>  [['[ ]', '[ ]'], ['[X]', '[ ]']]  <<<< This is what I expect to see
[1]

placing:  0
col:  0
row:  0
[X]
[['[X]', '[ ]'], ['[X]', '[ ]']]
>>>>  [['[X]', '[ ]'], ['[X]', '[ ]']]  <<<< This is what I expect to see
[1, 0]

placing:  3
col:  1
row:  1
[X]
[['[X]', '[X]'], ['[X]', '[X]']]
>>>>  [['[X]', '[ ]'], ['[X]', '[X]']]  <<<< This is what I expect to see
[1, 0, 3]

placing:  2
col:  0
row:  1
[X]
[['[X]', '[X]'], ['[X]', '[X]']]
>>>>  [['[X]', '[X]'], ['[X]', '[X]']]  <<<< This is what I expect to see
[1, 0, 3, 2]

但是,我已经指出了我希望看到的以&#39;&gt;&gt;&gt;&gt;&#39;&#39;在上面的输出中。

问:在我的代码中,我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为您的代码是正确的,但可能代码中没有显示错误。

您没有向我们展示board的初始化,我尝试使用board = [[""]*board_size] * board_size,获得与您所示相同的输出。在这种情况下,董事会实际上不是你的“列表中的列表”,它是一个列表,重复“board_size”次,所以一旦你改变了一个列表,你就改变了所有这些。

我将电路板初始化更改为board = [[""]*board_size for i in range(board_size)],然后我得到了正确答案。

您可以使用此代码检查列表中的列表是否是相同的列表:

import random
board_size = 2
number_of_squares_on_board = board_size * board_size

# good list:
board = [[""]*board_size for i in range(board_size)] 
# wrong list:
board = [[""]*board_size] * board_size
# check if they were the same
for _list in board:
    print(id(_list))

computers_places = []

while len(computers_places) < number_of_squares_on_board:

    placing = random.randint(0, number_of_squares_on_board-1)

    if placing not in computers_places:
        computers_places.append(placing)
        row = int(placing / board_size)
        column = int(placing % board_size)
        # print(computers_places)
        print("\nplacing: ", placing)
        print("col: ", column)
        print("row: ", row)

        column_list = board[column]
        column_list[row] = "[X]"

        print(board[column][row])
        print(board)
        print(computers_places)