Python 就地更新函数参数?

标签 python

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

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/

相关文章:

python - 将文本文件转换为json格式或过滤掉键值对

python - 尝试在 mysql-python 中使用我的添加和删除函数时出现错误

python - 在 shell 脚本中使用 shebang

python - 在 Python 中建模图形

python - 无法使用 pytest 在测试中导入模拟

python - Python导入的效率

python - 不能在 numpy 数组上使用/=

python - 使用 numpy 数组与 DataFrame 屏蔽 pandas DataFrame

python - GStreamer-关键 ** : gst_element_make_from_uri: assertion 'gst_uri_is_valid (uri)' failed

python - 从 Python 修改 Microsoft Outlook 联系人