通过将它传递给函数来修改python中的列表 [英] Modifying a list in python by passing it to a function

查看:139
本文介绍了通过将它传递给函数来修改python中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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(魔术师)

在这种情况下,您可以分配魔术师 to make_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 the magicians 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 in magicians , it replaces l in the function argument so the python interpreter actually sees magicians = ['The ... ?

解决方案

When you assign it to l, you are redefining l, not modifying it. Use l[:] 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 to make_great(['Tom']):

magicians = make_great(['Tom'])
print(magicians)

这篇关于通过将它传递给函数来修改python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆