Python - 函数更改输入列表,虽然我做了一个副本

标签 python list python-2.7

我正在编写一个小的 python 脚本,它打印出一个行列表,其中行本身是一个字符串列表。这就是函数的作用。它应该将列表作为输入并打印出漂亮的版本,而不实际更改列表。我可以让它打印出正确的输出。但是经过仔细检查,它也会更改原始列表,尽管我在函数中做的第一件事是使用此 grid_copy = grid[:]

制作原始列表的副本

问题:脚本将任何 '' 转换为 ' ' 尽管我没有修改列表

[['X', 'X', ''], ['', 'O', 'O'], ['O', 'X', '']]

进入:

[X] [X] [ ]

[ ] [O] [O]

[O] [X] [ ]

我不知道是什么导致列表被更改,除了我在开始制作副本时,我没有在哪里引用原始列表。

我添加的一些有用的注释使我的代码更容易理解我所做的事情。如果您运行代码,我还提供了一个测试用例。

def show_grid(grid):
    """
    grid: list. A list of lines, where the lines are a list of strings
    return: None
        Prints the grid out in the classic 3x3
    """
    grid_copy = grid[:]  # make a copy so we do not want to actually change grid
    len_grid = len(grid_copy)  # I use this so much, might as well store it

    # add whitespaces to make each single spot the same width
    len_digits = len(str((len(grid_copy)**2)))  # the number of chars wide the highest number is
    # modification happens somewhere vvv
    for line in range(len_grid):
        for char in range(len_grid):
            grid_copy[line][char] = str(grid_copy[line][char]).rjust(len_digits)  # proper white spaces

    # modification happens somewhere ^^^

    # add brackets, THIS IS NOT WHERE THE PROBLEM IS
    for line in grid_copy:
        print('[' + '] ['.join(line)+']\n')  # print each symbol in a box


# TESTING TESTING
test_grid = [['X', 'X', ''], ['', 'O', 'O'], ['O', 'X', '']]
print('test_grid before: {}'.format(test_grid))
show_grid(test_grid)  # this should not modify test_grid, but it does
print('test_grid after: {}'.format(test_grid))

输出:

test_grid before: [['X', 'X', ''], ['', 'O', 'O'], ['O', 'X', '']]
[X] [X] [ ]

[ ] [O] [O]

[O] [X] [ ]

test_grid after: [['X', 'X', ' '], [' ', 'O', 'O'], ['O', 'X', ' ']]

最佳答案

当您在列表的列表上编写 grid_copy = grid[:] 时,您只是复制最顶层的列表,而不是列表本身的元素。这称为浅拷贝,与深拷贝相对。你应该写

grid_copy = [x[:] for x in grid]

grid_copy = copy.deepcopy(grid)

关于Python - 函数更改输入列表,虽然我做了一个副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21640276/

相关文章:

python - 从 python 中的另一个排序列表中删除排序列表的快速和 pythonic/clean 方法是什么?

python - iPython notebook 中的 PySpark 在使用 count() 和 first() 时引发 Py4JJavaError

python - 在 Python 类中继承 Cython 类

python - 未知命令 : 'collectstatic' Django 1. 7

Python,压缩多个列表,其中一个列表每个需要两个项目

java - 如何从 java 中的方法返回 Integer 或 int 和列表?

python - 如何将元组列表转换为以索引为键的字典

python - imp.load_source 另一个文件而不是 .py ,但 .py 也存在于该目录中

python-2.7 - 使用python通过LAN记录,流式传输和接收音频

python - 使用 eval 将 json 转换为 dict 是一个不错的选择吗?