python函数如何改变参数而不是形式参数?
我试图使用python基本库编码1024。在这个过程中,我尝试将一个列表[0,2,4,4]变成[0,2,8,0]。所以这是我的测试代码。这是非常简单的。
I am trying to code "1024" using python basic library. In the process I try to make a list [0, 2, 4, 4] become [0, 2, 8, 0]. So here is my test code. It's very easy one.
def merger(a, b):
if a == b:
a += b
b = 0
numlist = [0, 2, 4, 4]
merger(numlist[0], numlist[1])
merger(numlist[1], numlist[2])
merger(numlist[2], numlist[3])
print (numlist)
所以当我尝试进行合并时。我期待输出[0,2,8,0]。但是,它给了我[0,2,4,4]。我想也许是因为我只是改变了函数的局部变量a b而不是实际的参数?但是,如果我想要发生这种情况,我该怎么办? Thx!
So when I try to conduct merge. I expected the output [0, 2, 8, 0]. However it gives me [0, 2, 4, 4] instead. I think maybe it's because I just changed the local variable of my function a b rather than the actual parameter? But If I want this to happen, what should I do? Thx!
我想知道一般情况下,如果我想要一个函数不会返回任何东西,而只是改变我作为参数传递的变量的值。我可以如何实现它?
I think I want to know generally if I want a function not return anything but just change value of the variable I passed as parameter. How can I achieve it?
您可以将列表和索引传递给函数:
You can pass the list and indexes to the function:
def merger(l, a, b):
if l[a] == l[b]:
l[a] += l[b]
l[b] = 0
numlist = [0, 2, 4, 4]
merger(numlist, 0, 1)
merger(numlist, 1, 2)
merger(numlist, 2, 3)
print(numlist)
由于列表对象将通过引用传递,函数内部列表中的任何更改将在函数调用后生效。
As list object will be passed by reference and any changes on the list inside the function will be effective after the function call.