且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用python中的函数对列表进行突变?

更新时间:2023-02-11 08:03:58

func(s):
   s[:] = whatever after mutating
   return s

x = a list of strings
print func(x)
print x

您实际上不需要返回任何内容:

You don't actually need to return anything:

def func(s):
    s[:] = [1,2,3]

x = [1,2]
print func(x)
print x # -> [1,2,3]

这完全取决于您的实际操作,在您实际更改传入的原始对象/列表时,追加或列表的任何直接突变都将反映在函数外部.如果您正在做的事情创建了一个新对象并且您希望反映在设置s[:] =..中传递的列表中的更改将更改原始列表.

It all depends on what you are actually doing, appending or any direct mutation of the list will be reflected outside the function as you are actually changing the original object/list passed in. If you were doing something that created a new object and you wanted the changes reflected in the list passed in setting s[:] =.. will change the original list.