Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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 3.x python 3关于使用[:]复制列表的混淆_Python 3.x - Fatal编程技术网

Python 3.x python 3关于使用[:]复制列表的混淆

Python 3.x python 3关于使用[:]复制列表的混淆,python-3.x,Python 3.x,假设L是一个列表,f和g是定义函数 def function(L,f,g): newL = list() for i in L: if g(f(i)) == True: newL.append(i) L[:] = newL if len(L) == 0: return -1 else: return max(L) def f(i): return i + 2 def g(

假设L是一个列表,f和g是定义函数

def function(L,f,g):
    newL = list()
    for i in L:
        if g(f(i)) == True:
            newL.append(i)

    L[:] = newL

    if len(L) == 0:
        return -1
    else:
        return max(L)

def f(i):
    return i + 2
def g(i):
    return i > 5

L = [0, -10, 5, 6, -4]
print(function(L, f,g))
print(L)
使用L=newL[:]将导致print(L)打印L=[0,-10,5,6,-4]。 但是如果在函数中我使用L[:]=newL,print(L),这将使print(L)给出newL[5,6]的结果,这就是我想要的
对我来说,L=newL[:]和L[:]=newL都会给出相同的结果。但事实并非如此。那么,有人能给我解释一下吗?

这是一个范围问题。在全局空间中创建的列表在函数中可以更改,因为使用此行:

L[:] = newL
您操作的是对全局列表的引用,而不是它的本地副本。因此,程序的最后一行将打印更改的列表。鉴于本版本:

L = newL[:]
…正在对列表的本地副本进行操作,因此程序的最后一行按函数调用之前的方式打印全局

使用此修改版本:

def function(L,f,g):
    newL = list()
    for i in L:
        if g(f(i)) == True:
            newL.append(i)

    L = newL[:]
    #L[:] = newL

    print('inner L = ', L)
    if len(L) == 0:
        return -1
    else:
        return max(L)

def f(i):
    return i + 2
def g(i):
    return i > 5

L = [0, -10, 5, 6, -4]
print(function(L, f,g))
print('outer L =', L)

我不明白这个问题?你不明白哪一部分
L[:]=newL
newL
做了一个浅显的复制,它改变了列表
L
,这样
L
就是现在的副本。如果我使用L=newL[:]print(L)会给我[0,-10,5,6,-4],但是如果我使用L[:]=newL print(L)会给我[5,6],这就是我想要的。我的问题是,对我来说,它们都是相同的,但我认为,事实上,它们并没有产生相同的结果。为什么?可能的重复可能的重复