将不同的对象附加到列表中,但列表会导致重复相同的对象

时间:2013-07-17 17:05:29

标签: python list for-loop

我试图在棋盘上创建一个返回n-queens状态的所有邻居节点的函数,下面是我的代码,主要是根据参数输入状态生成一个邻居节点列表。 / p>

#Generate neighboring state's function
def generate_neighbor_node (cur_state):
    current = cur_state
    neighbor = current
    neighbor_list = []
    for i in range(qs):
        chg_value = neighbor[i]
        chg_value +=1
        if chg_value == qs:
            chg_value =0
        neighbor[i] = chg_value 
        print neighbor       
        neighbor_list.append(neighbor)
    #Reverse the process, to change the node value back to original for next
    #loop to generate another valid neighbor state
        chg_value -=1
        if chg_value == -1:
           chg_value = (qs-1)
        neighbor[i] = chg_value    

   return neighbor_list                

print board
ai = generate_neighbor_node(board)
print ai

The output is like this:
1. [1, 3, 2, 0]
2. [2, 3, 2, 0]
3. [1, 0, 2, 0]
4. [1, 3, 3, 0]
5. [1, 3, 2, 1]
[[1, 3, 2, 0], [1, 3, 2, 0], [1, 3, 2, 0], [1, 3, 2, 0]]

但我真正想要的是要包含的列表是数组2,3,4和5但不是1 怎么做?请帮助,谢谢。

1 个答案:

答案 0 :(得分:1)

每当您致电neighbor_list.append(neighbor)时,您只需添加对neighbor的引用,而不是新列表。这意味着neighbor_list中的每个列表都只是neighbor的当前值。

要解决此问题,您应该像这样复制列表:

neighbor_list.append(copy.copy(neighbor)

Documentation for copy