Python函数正在改变传递参数的值 [英] Python function is changing the value of passed parameter

查看:48
本文介绍了Python函数正在改变传递参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我开始的一个例子

mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]]

def testfun(passedvariable):
    for row in passedvariable:
        row.append("Something else")
    return "Other answer"


otheranswer = testfun(mylist)
print mylist

我希望 mylist 不会改变.

然后我尝试删除该临时列,但没有用:

I then tried this to remove that temporary column, but that didn't work:

mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]]

def testfun(passedvariable):
    for row in passedvariable:
        row.append("Something else")

    # I'm now finished with the "Something else" column, so remove it
    for row in passedvariable: row = row[:-1]
    return "Other answer"


otheranswer = testfun(mylist)
print mylist

我想尝试使用不同的参考:

I think tried to use a different reference:

mylist = [["1", "apple"], ["2", "banana"], ["3", "carrot"]]

def testfun(passedvariable):
    copyofdata = passedvariable
    for row in copyofdata:
        row.append("Something else")

    # I'm now finished with the "Something else" column, so remove it
    for row in copyofdata: row = row[:-1]
    return "Other answer"


otheranswer = testfun(mylist)
print mylist

我已经写了几个月的 Python 小脚本,但以前从未遇到过这种情况.我需要了解什么,以及如何将列表传递给函数并临时操作它(但保持原始状态不变?).

I've written little Python scripts for a few months now, but never come across this before. What do I need to learn about, and how do I pass a list to a function and temporarily manipulate it (but leave the original untouched?).

推荐答案

Python 通过共享传递一切(作为值传递的引用,请参阅 通过共享调用),但是集成的数字和字符串类型是不可变的,因此如果您更改它们,则引用的值将更改,而不是对象本身.对于像列表这样的可变类型,请复制一份(例如 list(passedvariable)).如果您正在修改列表中的可变对象(它只能包含引用!),您将需要执行深度复制,为此使用

Python passes everything by sharing (references passed as value, see call by sharing), however the integrated numeric and string types are immutable, so if you change them the value of the reference is changed instead of the object itself. For mutable types like list, make a copy (e.g. list(passedvariable)). If you are modifying mutable objects within a list (which can only contain references!) you will need to perform a deep copy, to do so use

import copy
copy.deepcopy(passedvariable)

参见 https://docs.python.org/2/library/copy.html(自 Python 2.6 起可用)

See https://docs.python.org/2/library/copy.html (available since Python 2.6)

请注意,由于引用本身是按值传递的,因此您不能将作为参数传递的引用更改为指向函数之外的其他内容(即,passedvariable = passvariable[1:] 不会更改在函数外看到的值).一个常见的技巧是传递一个包含一个元素的列表并更改该元素.

Note that since references themselves are passed by value, you cannot change a reference passed as a parameter to point to something else outside of the function (i. e. passedvariable = passedvariable[1:] would not change the value seen outside the function). A common trick is to pass a list with one element and changing that element.

这篇关于Python函数正在改变传递参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆