Python:覆盖作为参数传递的列表,对外部作用域可见更改

Bła*_*lik 0 python

我正在尝试编写一个执行此操作的代码:

the_list = ['some list', 0, 1, 2]

def change(l):
    x = ['some other list', 3, 4, 5]
    l = x

change(the_list)
print(the_list)    # ['some other list', 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

我的问题基本上大多数人必须处理的问题相反.我正在尝试将列表的每个元素分配xchange作为参数传递给函数的列表中l,以便更改对外部作用域可见.

我没有使用return语句,因为使用函数参数进行操作会使我编写的代码更加清晰.这对我来说更有意义.

什么是最pythonic的方式来做到这一点?

nie*_*mmi 5

您可以执行以下操作来替换l函数内的内容change:

def change(l):
    x = ['some other list', 3, 4, 5]
    l[:] = x
Run Code Online (Sandbox Code Playgroud)

这将使用给定的iterable内容替换切片范围(在本例中为整个列表).