1

鉴于此源列表:

source_list = [2, 3, 4]

这个功能:

def function(list_in):
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in

正如预期的那样,我得到:

>>> function(source_list)
[1, 2, 3, 4, 5]

但是,如果我在函数之外调用变量 source_list ,我仍然会得到:

>>> source_list
[1, 2, 3, 4, 5]

是否有另一种方法可以修改(特别是附加/前置)函数中的列表,以使原始列表不被更改?

4

5 回答 5

2

If you are the caller of the function, you can copy first

new_list = function(source_list[:])

This has the advantage that the caller decides whether it wants its current list to be modified or not.

于 2020-11-23T05:44:13.937 回答
1

If you have access to the function, you can copy the list passed:

like this:

def function(list_in_):     # notice the underscore suffix
    list_in = list_in_[:]   # copy the arg into a new list
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in          # return the new list

otherwise you can call the function with a copy of your source_list, and decide if you want a new list, or if you prefer the source_list mutated, as demonstrated by @tdelaney

于 2020-11-23T05:41:41.530 回答
0

You can use the copy() method on the list:

new_list = function(source_list.copy())
于 2020-11-23T05:45:58.147 回答
0

只需在您的函数中添加一行:

   def function(list_n):
    #Do a copy of your list
    list_in = list_n.copy()
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in
于 2020-11-23T05:46:39.213 回答
0

尝试这个。由于在代码中运行函数时源列表被修改,因此您无法保留源列表。

source_list = [2, 3, 4]
list_in=source_list.copy()
def function(list_in):
    list_in.append(5)
    list_in.insert(0, 1)
    return list_in
print(function(list_in))
print(source_list)
于 2020-11-23T05:49:09.013 回答