简体   繁体   English

为什么 function 不改变它的论点?

[英]Why doesn't the function change it's argument?

def func(l):
    l = l + l
    return ()
lst = [22, 33, 13]
func(lst)
print(lst)

The output is [22, 33, 13] . output 是[22, 33, 13] Why is it not [22, 33, 13, 22, 33, 13] ?为什么不是[22, 33, 13, 22, 33, 13]

Inside the function you made the reference l point to a new list object l + l .在 function 中,您将参考l指向一个新列表 object l + l The outside reference lst still points to the original list object.外部引用lst仍然指向原始列表object。

If the function had instead modified the list object itself, by appending to it for example, you would see the effect after the function ended.如果 function 修改了列表 object本身,例如通过附加到它,您将看到 function 结束后的效果。

def func(l):
    l.append(42)
    print(l)
    return () # Not really needed.

lst = [22, 33, 13]
func(lst)
print(lst)

If you want to get the desired result, try using the list extend method.如果您想获得所需的结果,请尝试使用列表extend方法。

def func(l):
    l.extend(l)

lst = [22, 33, 13]
func(lst)
print(lst) # prints [22, 33, 13, 22, 33, 13]

Try this:尝试这个:

def func(l):
    l = l + l
    return l  # return l from function space.
lst = [22, 33, 13]
lst = func(lst) # need to update lst
print(lst)

For starters your function returns a tuple , an empty one.对于初学者,您的 function 返回一个tuple ,一个空的。 It does not do anything to the list you passed it.它不会对您传递给它的列表做任何事情。

In any case even if you fix your function to actually return the list, you would still have to assign in to something, like below:在任何情况下,即使您修复了 function 以实际返回列表,您仍然需要分配一些内容,如下所示:

def func(l):
    l = l + l
    return l

lst = [22, 33, 13]
new_lst  = func(lst)

print(lst)
print(new_lst)

>>[22, 33, 13]
>>[22, 33, 13, 22, 33, 13]

Inside the function, in the line l = l + l , you're creating a new list l based on the list passed in as an argument and losing the reference to the old list passed in as an argument in a single line.在 function 中,在l = l + l行中,您正在创建一个新列表l基于作为参数传入的列表,并在一行中丢失对作为参数传入的旧列表的引用

You never modify the list outside the function (eg what could be done by using the append or extend method), and you never return the new list inside the function, so you don't see any changes after the function is done executing. You never modify the list outside the function (eg what could be done by using the append or extend method), and you never return the new list inside the function, so you don't see any changes after the function is done executing.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM