更改列表列表中的值

时间:2017-05-10 08:41:14

标签: python python-3.x

我在更改列表列表的值时遇到了困难。我无法弄明白为什么

我正在构建一个创建一个星塔(看起来像一棵圣诞树)的功能

def tower_builder(n_floors):
    tower = []
    real_tower = []
    block_len = 1 + (2 * (n_floors-1))
    tower_block = []
    center_star = int(block_len / 2)
    n = 0

    #Creates a list of the top block of the tower with a star at the center and spaces for all other list values
    for i in range(block_len):
        if i == center_star:
            tower_block.append("*")
        else:
            tower_block.append(" ")

    #Replicates the top block for other blocks and will change subsequent blocks to have stars in the proper list indexes
    for n in range(n_floors):
        start_index = 0
        end_index = 0
        star_len = 0
        start_index = center_star - n
        end_index = center_star + n
        star_len = (end_index - start_index) + 1
        tower.append(tower_block)
    tower[0][0] = 3
    return(tower)

出于某种原因,在

之后
tower[0][0] = 3

它不是修改第一个列表中的第一个条目,而是修改所有列表中的第一个条目。

tower_builder(3)
>>>> [[3, ' ', '*', ' ', ' '], [3, ' ', '*', ' ', ' '], [3, ' ', '*', ' ', ' ']]

我期望它返回:

    tower_builder(3)
>>>> [[3, ' ', '*', ' ', ' '], [' ', ' ', '*', ' ', ' '], [' ', ' ', '*', ' ', ' ']]

我必须对列表的工作方式产生某种根本性的误解。有人可以解释为什么会这样吗?

0 个答案:

没有答案