python函数在列表中无明显原因地递增变量

2024-09-29 23:21:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我是Python的新手,我不明白这个问题。代码如下:

(敌人和玩家都是包含2个变量的列表,例如[1,2])

def AIenemyTurn(enemy,playerPos):
    startPos = enemy
    print(startPos)
    potEnemyPos = enemy
    if playerPos[0] > enemy[0]:
        potEnemyPos[0] += 1
    elif playerPos[0] < enemy[0]:
        potEnemyPos[0] -= 1
    elif playerPos[1] > enemy[1]:
        potEnemyPos[1] += 1
    elif playerPos[1] < enemy[1]:
        potEnemyPos[1] -= 1
    if potEnemyPos not in rocks:
        print(potEnemyPos)
        print(startPos)
        return potEnemyPos
    else:
        return startPos

这就是Shell中显示的内容:

[1, 2]
[2, 2]
[2, 2]

为什么startPos在第二次打印时会有所不同?我没有在函数中修改它


Tags: 代码列表returnifdef玩家printelif
1条回答
网友
1楼 · 发布于 2024-09-29 23:21:48

这是因为列表是可变的,所以将它们赋给两个不同的值意味着这两个值引用同一个列表:

>>> x = [2, 2]
>>> y = x
>>> z = x
>>> z[1] = 0
>>> z
[2, 0]
>>> y
[2, 0]

您还可以通过查看id进行检查:

>>> id(y)
4300734408
>>> id(z)
4300734408
>>> id(x)
4300734408
>>> 

解决这个问题的一种方法是调用startPos = list(enemy),因为强制转换到list会生成一个新列表:

>>> a = [1, 2]
>>> b = list(a)
>>> id(a)
4300922320
>>> id(b)
4300922680
>>> 

这是您编辑的代码:

def AIenemyTurn(enemy,playerPos):
    startPos = list(enemy)
    print(startPos)
    potEnemyPos = enemy
    if playerPos[0] > enemy[0]:
        potEnemyPos[0] += 1
    elif playerPos[0] < enemy[0]:
        potEnemyPos[0] -= 1
    elif playerPos[1] > enemy[1]:
        potEnemyPos[1] += 1
    elif playerPos[1] < enemy[1]:
        potEnemyPos[1] -= 1
    if potEnemyPos not in rocks:
        print(potEnemyPos)
        print(startPos)
        return potEnemyPos
    else:
        return startPos

相关问题 更多 >

    热门问题