如何使用python中的函数对列表进行突变? [英] How to mutate a list with a function in python?
问题描述
这是我写的描述我的问题的伪代码:-
Here's a pseudocode I've written describing my problem:-
func(s):
#returns a value of s
x = a list of strings
print func(x)
print x #these two should give the SAME output
当我最后打印x的值时,我希望它是func(x)返回的值.我只能通过编辑功能(而不设置x = func(x)
)
When I print the value of x in the end, I want it to be the one returned by func(x). Can I do something like this only by editing the function (and without setting x = func(x)
)
推荐答案
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.
这篇关于如何使用python中的函数对列表进行突变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!