Python 列表分配无效

Python list assignment not working

所以我有一个列表,在 for 循环内,我附加了一组结构为列表的坐标,但一旦返回,它只包含最后生成的坐标,并替换主列表中的所有其他项目。 经过仔细检查,每次我追加一些东西时,它都会用当前坐标替换主列表中的所有项目。 为什么? 源代码可能无济于事,听起来就是这样。 谢谢! 这里有一些代码:

def createLab(size=16):
maze = createMaze()
answerPath=[]
visual=['o']*(size**2)
pos=[(size**2)/2,(size**2)/2]
lat='north'
for move in maze:
    #print move, lat, pos
    #print answerPath
    answerPath.append(pos)
    #answerPath='[%s, %s]' % (answerPath,pos)
    if move=='straight':
        if lat=='north': pos[1]=pos[1]+size
        elif lat=='south': pos[1]=pos[1]-size
        elif lat=='east': pos[0]=pos[0]+1
        elif lat=='west': pos[0]=pos[0]-1

    elif move=='left':
        if lat=='north': pos[1]=pos[1]-1; lat='west'
        elif lat=='south': pos[1]=pos[1]+1; lat='east'
        elif lat=='east': pos[0]=pos[0]+size; lat='north'
        elif lat=='west': pos[0]=pos[0]-size; lat='south'

    elif move=='right':
        if lat=='north': pos[1]=pos[1]+1; lat='east'
        elif lat=='south': pos[1]=pos[1]-1; lat='west'
        elif lat=='east': pos[0]=pos[0]-size; lat='south'
        elif lat=='west': pos[0]=pos[0]+size; lat='north'
    #print pos
    #print; print
return answerPath, maze, pos

没有代码,我们真的帮不了你太多。从您的描述来看,您似乎没有将新坐标附加到列表中,而是覆盖了同一个列表。

请向我们提供相关代码。

在您的代码中尝试类似 .append 的内容。例如。

列表=[一、二、三]

list.append(四)

打印(列表)

print 现在应该为您提供以下结果。

一二三四

希望对你有所帮助。

您正在循环之前创建一个 pos 列表,并且您一遍又一遍地将完全相同的 pos 附加到 answerPath,并修改相同的 pos 一遍又一遍。

作为解决方案,在每次迭代开始时创建一个新的 pos,使用切片符号进行浅拷贝:

def createLab(size=16):
    maze = createMaze()
    answerPath=[]
    visual=['o']*(size**2)
    pos=[(size**2)/2,(size**2)/2]
    lat='north'
    for move in maze:
        pos = pos[:] #pos is now a new list with the same values as the previous pos
        #Alternatively: pos = list(pos)
        answerPath.append(pos)

        if move=='straight':
            if lat=='north': pos[1]=pos[1]+size
            elif lat=='south': pos[1]=pos[1]-size
            elif lat=='east': pos[0]=pos[0]+1
            elif lat=='west': pos[0]=pos[0]-1

        elif move=='left':
            if lat=='north': pos[1]=pos[1]-1; lat='west'
            elif lat=='south': pos[1]=pos[1]+1; lat='east'
            elif lat=='east': pos[0]=pos[0]+size; lat='north'
            elif lat=='west': pos[0]=pos[0]-size; lat='south'

        elif move=='right':
            if lat=='north': pos[1]=pos[1]+1; lat='east'
            elif lat=='south': pos[1]=pos[1]-1; lat='west'
            elif lat=='east': pos[0]=pos[0]-size; lat='south'
            elif lat=='west': pos[0]=pos[0]+size; lat='north'
    return answerPath, maze, pos

要了解您和我的示例中 pos 的实际情况,我建议阅读 Wesley Chun's excellent slides on Python's Memory Model