我正在尝试编写一个执行此操作的代码:
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)
我的问题基本上与大多数人必须处理的问题相反.我正在尝试将列表的每个元素分配x到change作为参数传递给函数的列表中l,以便更改对外部作用域可见.
我没有使用return语句,因为使用函数参数进行操作会使我编写的代码更加清晰.这对我来说更有意义.
什么是最pythonic的方式来做到这一点?
您可以执行以下操作来替换l函数内的内容change:
def change(l):
x = ['some other list', 3, 4, 5]
l[:] = x
Run Code Online (Sandbox Code Playgroud)
这将使用给定的iterable内容替换切片范围(在本例中为整个列表).
| 归档时间: |
|
| 查看次数: |
233 次 |
| 最近记录: |