如何在python中使用函数改变列表?

Rit*_*rma 9 python function mutable

这是我写的描述我的问题的伪代码: -

func(s):
   #returns a value of s

x = a list of strings
print func(x)
print x #these two should give the SAME output
Run Code Online (Sandbox Code Playgroud)

当我最后打印x的值时,我希望它是func(x)返回的值.我只能通过编辑功能(并且不设置x = func(x))来执行此类操作

bak*_*kal 8

这已经是它的行为,该函数可以改变列表

>>> l = ['a', 'b', 'c'] # your list of strings
>>> def add_something(x): x.append('d')
...
>>> add_something(l)
>>> l
['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

但请注意,您不能以这种方式改变原始列表

def modify(x):
    x = ['something']
Run Code Online (Sandbox Code Playgroud)

(以上将分配x但不是原始列表l)

如果要在列表中放置新列表,则需要以下内容:

def modify(x):
    x[:] = ['something'] 
Run Code Online (Sandbox Code Playgroud)

  • 切记不要在函数体中分配“ x”。否则,“ x”将成为局部变量(函数名称空间中的对象),并将“覆盖”传递给函数的参数。 (2认同)

Pad*_*ham 6

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

x = a list of strings
print func(x)
print x
Run Code Online (Sandbox Code Playgroud)

你实际上不需要返回任何东西:

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

x = [1,2]
print func(x)
print x # -> [1,2,3]
Run Code Online (Sandbox Code Playgroud)

这一切都取决于你实际在做什么,附加或列表的任何直接变异将反映在函数外部,因为你实际上正在改变传入的原始对象/列表.如果你正在做一些创建一个新对象的东西,你想要在设置中传递的列表中反映的更改s[:] =..将更改原始列表.

  • 很难搜索像`[:]`这样的东西。这是非常有用的代码和平。 (2认同)