在python3中添加子列表到列表不起作用

时间:2017-12-07 17:19:26

标签: python-3.x list append

我在Python3中有一个非常奇怪的问题。我有一些代码从整数列表生成一些不同的列表(这完全不相关)。

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = state

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state

现在我要做的就是在保存状态的某个列表中添加下一个状态。这是我的代码:

l = [0, 2, 7, 0]
seen_states = []

for _ in range(10):
    print(l)
    seen_states += [l]
    l = get_next_state(l)

print(seen_states)

出于某种原因,我打印时正确分配了列表l,但未将其正确添加到已显示状态列表中。请注意,我还尝试了seen_states.append(l)而不是+= [l]。有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:0)

new_state = state[:]中使用get_next_state(复制列表而不是引用原文)会产生以下输出:

[0, 2, 7, 0]
[2, 4, 1, 2]
[3, 1, 2, 3]
[0, 2, 3, 4]
[1, 3, 4, 1]
[2, 4, 1, 2]
[3, 1, 2, 3]
[0, 2, 3, 4]
[1, 3, 4, 1]
[2, 4, 1, 2]
[[0, 2, 7, 0], [2, 4, 1, 2], [3, 1, 2, 3], [0, 2, 3, 4], [1, 3, 4, 1], [2, 4, 1, 2], [3, 1, 2, 3], [0, 2, 3, 4], [1, 3, 4, 1], [2, 4, 1, 2]]

不确定这是否是您想要的输出,因为您没有指定您获得的“错误”输出

答案 1 :(得分:0)

要防止出现这些问题,请使用copy, deepcopylist[:]

import copy

def get_next_state(state):

    max_val = max(state)
    max_index = state.index(max_val)
    new_state = copy.deepcopy(state)

    for n in range(max_val + 1):
        new_state[max_index] -= 1
        new_state[(n + max_index) % len(state)] += 1

    return new_state

您要在功能中发送列表l。将其指定给其他名称时,您不会复制,而是引用原始对象。对这些列表的任何修改都是对原始对象的更改。