【发布时间】:2014-05-31 14:07:45
【问题描述】:
这是我开始的一个例子
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 没有改变。
然后我尝试删除该临时列,但没有奏效:
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
我想尝试使用不同的参考:
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 脚本,但以前从未遇到过。我需要了解什么,以及如何将列表传递给函数并临时对其进行操作(但保持原件不变?)。
【问题讨论】:
-
copyofdata不是该列表的副本,它只是对同一列表的另一个引用。 -
其他答案 = testfun(mylist[:])。这是在发送之前复制列表的 Pythonesque 方式
-
testfun(list(mylist))