列表的非破坏性副本

时间:2014-04-15 00:01:19

标签: python python-3.x

如何使用b = a [:]?

创建列表的非破坏性副本

4 个答案:

答案 0 :(得分:2)

new_board = board[:]替换为:

new_board = [x[:] for x in board]

board是可变列表的列表。 board[:]制作board的副本,但不会复制其包含的可变列表。上面的代码制作了这些副本。

或者,使用copy模块(import copy):

new_board = copy.deepcopy(board)

答案 1 :(得分:1)

list_ [:]会复制第一级列表,而不是其中的第二级列表。

两个获得(所有,真正的)级别,尝试copy.deepcopy(list _)。

答案 2 :(得分:0)

我已经与

合作了
def insert_black_tiles(board, num_black_spaces):
    new_board = board[:]
    while num_black_spaces > 0:
        a = random.randint(0,2)
        b = random.randint(0,2)
        c = 'black'
        if new_board[a][b] != 'black':
            new_board[a][b] = c
            num_black_spaces -= 1
    return new_board

在你的版本中,有时黑色空间会再次变黑。

编辑:这是另一个具有库函数的变体:

def insert_black_tiles(board, num_black_spaces):
    new_board = [x[:] for x in board]
    three_by_three = [(i,j) for i in range(3) for j in range(3)]
    for (a,b) in random.sample(three_by_three, 8):
        new_board[a][b] = 'black'
    return new_board

答案 3 :(得分:0)

尽管其他人的答案在深度与浅层的语义方面要好得多。我会提到它的使用方式通常更好(在我看来):

a = list(b)

而不是

a = b[:]

因为它更加明确。