通过将它传递给函数来修改python中的列表 [英] Modifying a list in python by passing it to a function
问题描述
我有以下python代码:
def make_great(l):
l = [' (魔术师)
打印(魔术师)
魔术师= ['Tom']
make_great / pre>
print语句打印原始列表,而不是由
make_great()
函数修改的列表。我试图找出修改python列表的每个元素而不显式访问它的索引,然后重新分配该索引一个新值的方法。现在magicians
列表不会指向基于Python内存模型的理解所形成的新列表吗?我猜测我没有得到预期的结果,因为这是一个范围问题?但是当我传入magicians
时,它会替换函数参数中的l
,所以python解释器实际上会看到magicians = ['The ...
?解决方案c $ c> l ,你正在重新定义
l
,而不是修改它。使用l [:]
代替:
def make_great(l):
l [:] = ['伟大的魔术师+魔术师]
你也可以返回列表并重新定义
魔术师
:
def make_great(l ):
return ['魔术师的魔术师']
魔术师= ['Tom']
魔术师= make_great(魔术师)
print(魔术师)
在这种情况下,您可以分配
魔术师
tomake_great(['Tom'])
:
魔术师= make_great(['Tom'])
print(magicians)
I have the following python code:
def make_great(l): l = ['The great ' + magician for magician in l] magicians = ['Tom'] make_great(magicians) print(magicians)
The print statement prints the original list, not the one modified by the
make_great()
function. I was trying to figure out a way of modifying each element of a python list without explicitly accessing it's index and then reassigning that index a new value. Wouldn't themagicians
list now point to the new list formed by the comprehension based on Python's memory model ? I am guessing that I am not getting the desired results because this is a scoping issue ? But when I pass inmagicians
, it replacesl
in the function argument so the python interpreter actually seesmagicians = ['The ...
?解决方案When you assign it to
l
, you are redefiningl
, not modifying it. Usel[:]
instead:def make_great(l): l[:] = ['The great ' + magician for magician in l]
You could also return the list and redefine
magicians
:def make_great(l): return ['The great ' + magician for magician in l] magicians = ['Tom'] magicians = make_great(magicians) print(magicians)
In that case, you could assign
magicians
tomake_great(['Tom'])
:magicians = make_great(['Tom']) print(magicians)
这篇关于通过将它传递给函数来修改python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!