Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python在定义函数时为什么不使用return更改值_Python - Fatal编程技术网

python在定义函数时为什么不使用return更改值

python在定义函数时为什么不使用return更改值,python,Python,我没有返回f中的lst,为什么lst会改变 这是因为列表在python中的工作方式,它不会将函数发送到列表。它将函数发送到内存中已经存在的列表所在的位置,然后可以对其进行更改这是因为列表在Python中是可变的,并且您的函数会修改lst。事实上,它与缺少的return语句无关-这意味着如果您有x=f(lst),x将是None。如果您想在lst上执行f,而不改变它,请发送一份副本。下面是一个例子: >>> lst=[1] >>> def f(lst):

我没有返回f中的lst,为什么lst会改变

这是因为列表在python中的工作方式,它不会将函数发送到列表。它将函数发送到内存中已经存在的列表所在的位置,然后可以对其进行更改

这是因为列表在Python中是可变的,并且您的函数会修改
lst
。事实上,它与缺少的
return
语句无关-这意味着如果您有
x=f(lst)
x
将是
None
。如果您想在
lst
上执行
f
,而不改变它,请发送一份副本。下面是一个例子:

>>> lst=[1]
>>> def f(lst):
        lst[0]=3


>>> f(lst)
>>> lst
[3]
这张照片是:

lst = [1, 2, 3]

def fn(lst):
    print("in fn")
    lst[1] = 10

x = lst[::] # make a copy
print("X before is:", x)
fn(x)
print("X after is:", x)
print("Lst after calling fn with x but before using Lst is:", lst)
fn(lst)
print("Lst after is:", lst)
X before is: [1, 2, 3]
in fn
X after is: [1, 10, 3]
Lst after calling fn with x but before using Lst is: [1, 2, 3]
in fn
Lst after is: [1, 10, 3]