列表变量的值正在更改,尽管没有显式更改

2024-09-28 21:55:42 发布

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

变量'operations'是一个列表,它在for循环运行后正在更改,尽管它们没有明确表示其值要更改的行。这是我的密码:

validOperations = ['(', ')', '^', '*', '/', '+', '-']
operations = ['+', '*', '/']
newOp = operations  

for y in range(len(newOp) - 1):
        for z in range(len(newOp) - 1):
                if(validOperations.index(newOp[z]) > validOperations.index(newOp[z+1])):
                        oldVal = newOp[z]
                        newOp[z] = newOp[z+1]
                        newOp[z+1] = newOp[z]
                        print(newOp)
                        print(operations)

我该怎么做才能使操作的值保持不变


Tags: in密码列表forindexlenifrange
1条回答
网友
1楼 · 发布于 2024-09-28 21:55:42

newOP不是operatoions的副本newOpoperations的别名。这意味着当newOP改变时,operations也会改变。您需要明确地告诉Python复制您的列表:

newOp = operations[:]

但是,如果列表在嵌套中的深度超过一级,那么使用切片表示法将失败。必须改用^{}

相关问题 更多 >