gpt4 book ai didi

Python 就地更新函数参数?

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:19 26 4
gpt4 key购买 nike

我正在尝试创建一个函数来就地更新参数(主要是出于好奇):

def inplaceUpdate(f, inputs):
for i in inputs:
i = f(i)

我有三个输入:

x = 1
y = 2
z = 3

和函数f:

f = lambda i: i**2

我想运行以下代码:

inplaceUpdate(f, [x, y, z])

然后我希望 xyz 的值就地改变。这可能吗?

x = 1
y = 4
z = 9

最佳答案

在 Python 中,整数是不可变的。有个切题的问题here .

这个想法是您不能更改引用 xyz 的值。这意味着如果您这样做:

x = 2
y = 3
z = 4
some_func([x, y, z])

some_func 无法更改 变量 xy 的值z.

但是,列表是可变的,您可以这样做:

def some_func(l):
l[:] = [i*2 for i in l]

l = [2, 3, 4]
some_func(l)

print l # the array has changed

这确实会改变列表。这是因为操作 l[:]=... 分配给列表的包含,而不是重新分配引用——这将是 l=... .

关于Python 就地更新函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33939960/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com