Python 函数中的引用是如何工作的?

Python 函数中的引用是如何工作的?,python,python-2.7,reference,Python,Python 2.7,Reference,首先,我编写了第一个代码示例,但它不能正常工作。我更喜欢第一个样品,但只有第二个能正常工作。我不知道为什么第一个样本没有改变原始数组,但第二个却改变了。区别在哪里 第一个样本: import heapq def heap_sort(tab): heap = [] for i in tab: heapq.heappush(heap, i) tab = [heapq.heappop(heap) for _ in xrange(len(heap))] tem

首先,我编写了第一个代码示例,但它不能正常工作。我更喜欢第一个样品,但只有第二个能正常工作。我不知道为什么第一个样本没有改变原始数组,但第二个却改变了。区别在哪里

第一个样本:

import heapq

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    tab = [heapq.heappop(heap) for _ in xrange(len(heap))]

temp_tab = [4, 3, 5, 1]
heap_sort(temp_tab)
print temp_tab
import heapq

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    for i, _ in enumerate(tab):
        tab[i] = heapq.heappop(heap)

temp_tab = [4, 3, 5, 1]
heap_sort(temp_tab)
print temp_tab
印刷品:

[4, 3, 5, 1]
[1, 3, 4, 5]

第二个示例:

import heapq

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    tab = [heapq.heappop(heap) for _ in xrange(len(heap))]

temp_tab = [4, 3, 5, 1]
heap_sort(temp_tab)
print temp_tab
import heapq

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    for i, _ in enumerate(tab):
        tab[i] = heapq.heappop(heap)

temp_tab = [4, 3, 5, 1]
heap_sort(temp_tab)
print temp_tab
印刷品:

[4, 3, 5, 1]
[1, 3, 4, 5]

因为您只是在函数内部重新分配一个名为
tab
的新名称,所以它不会影响您定义的全局名称
tab
。 因此,将函数更改为实际返回值将起作用:

import heapq

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    # return the supposed tab value
    return [heapq.heappop(heap) for _ in xrange(len(heap))]

tab = [4, 3, 5, 1]
# assign the tab to the returned value
tab = heap_sort(tab)
print tab
[1, 3, 4, 5]

作为参考,read将帮助您了解Python中引用的工作原理。

您还可以使用
[:]
,这将更改传入的原始对象:

def heap_sort(tab):
    heap = []
    for i in tab:
        heapq.heappush(heap, i)
    tab[:] = [heapq.heappop(heap) for _ in xrange(len(heap))]
因此,您实际上是在更新原始的
选项卡
对象,而不是将名称
选项卡
重新指定给新对象

也可以使用生成器表达式,而不是构建整个列表:

tab[:] = (heapq.heappop(heap) for _ in xrange(len(heap)))
试试这个:

>>> def heap_sort(tab):
    heap=[]
    for i in tab:
        heapq.heappush(heap,i)
    heapq.heapify(heap)
    return heap

>>> t=heap_sort(t)
>>> print(t)
[1, 3, 5, 4]

在第一个示例中,如果您分配给
tab[:]
而不是
tab
,它会起作用。这段代码有什么意义?为什么不返回heap而不是将所有内容都推回到tab中?事实上,为什么不对列表进行排序并完全忘记堆的内容呢?但是如果我有不同的名称(tab1,无论什么),结果都是一样的。@WuJo,关键是,在函数内部,它们无法访问全局
选项卡
,一旦函数返回,它只会创建一个名为
选项卡
的新名称,新的
tab
值已被释放。@WuJo,因此您可以将全局
tab
重新分配给函数返回的值。