change在python是什么函数,Python:函数来改变'就地'的值?

I'd like to implement a function that allows the values of its arguments to be reallocated 'in place'.

As an example, a function that will increment argument x and decrement argument y. (This is just a simple example for illustration - the motivation is that X and Y are in fact single elements of a large dataframe; their expressions are unwieldy; and this operation will undergo many iterations.)

def incdec(x,y,d):

x += d

y -= d

Ideally this would be run as:

X = 5; Y = 7; d = 2

incdec(X,Y,d)

to find that the values are now X = 7 and Y = 5. But of course it doesn't work like that - I wondered why?

解决方案

Why does your function not change the final values of X and Y ?

In Python When a function with arguments is called,

copies of the values of the arguments are stored in local variables.

Indeed when you write

def incdec(x,y,d):

x += d

y -= d

the only thing that changes are the x and y that are IN THE function indec.

But at the end of the function local variables are lost.

To obtain what you want you should remember what the function did.

To remember those values AFTER the function you should re-assigne x and y like this:

def incdec(x,y,d):

x += d

y -= d

return (x,y)

# and then

X = 5; Y = 7; d = 2

X,Y = incdec(X,Y,d)

this works because X,Y are of type int.

What you also could do is using a list to have a direct access to the variables you want to change.

def incdec(list_1,d):

list_1[0] += d

list_1[1] -= d

#no return needed

# and then

X = 5; Y = 7; d = 2

new_list = [X, Y]

incdec(new_list,d) #the list has changed but not X and Y

Don t get me wrong, the arguments passed are still a copy as I said earlier but when you copy a list, only references are copied, but those are still looking at the same object. Here's a demo:

number = 5

list_a = [number] #we copy the value of number

print (list_a[0]) # output is 5

list_b = list_a # we copy all references os list_a into list_b

print(list_b[0]) # output is 5

list_a[0]=99

print(list_b[0]) # output is 99

print(number) # output is 5

as you can see list_a[0] and list_b[0] is one same object but number is a different one

That s because we copied the value of number and not the reference.

I recommend you to use the first solution.

I hope this helped.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值