Skip to main content
 首页 » 编程设计

python之为什么 sage 将本地 python 变量视为全局变量

2025年05月04日8lexus

sage 和 python 的新手,所以我不确定我在滥用哪个。我正在尝试定义以下作用于输入列表 A 的函数,但每次我输入该函数时都会影响 A 的全局值。如何使其在本地运行?

def listxgcd( A ): 
    g,s,t=xgcd(A.pop(0),A.pop(0)) 
    coeffs=[s,t] 
    while a!=[]: 
        g,s,t=xgcd(g,A.pop(0)) 
        coeffs=[s*i for i in coeffs] 
        coeffs=coeffs+[t] 
    return coeffs 

我试过设置 B=A 并在所有地方替换 B 但这也不起作用,我不明白。我需要声明某种 sage-y 变量吗?

def listxgcd( a ): 
    B=a 
    g,s,t=xgcd(B.pop(0),B.pop(0)) 
    coeffs=[s,t] 
    while B!=[]: 
        g,s,t=xgcd(g,B.pop(0)) 
        coeffs=[s*i for i in coeffs] 
        coeffs=coeffs+[t] 
    return coeffs 

非常感谢!

请您参考如下方法:

您正在将对容器对象的引用传递给您的 listxgcd 函数,该函数使用 pop 从该容器中检索元素。这不是范围问题,只是您直接在传递给函数的容器上操作的事实。

如果您不希望函数修改容器,请复制它:

import copy 
def listxgcd( Ain ): 
    A = copy(Ain) 
    ... 

或者更好的是,如果容器允许的话,使用索引访问元素:

... 
g,s,t=xgcd(A[0],A[1]) 
... 
for i in range(2,len(A)): 
    g,s,t=xgcd(g,A[i]) 
    ...