函数中的引用如何工作?

How do references in functions work?

首先,我编写了第一个代码示例,但它无法正常工作。我更喜欢第一个示例,但只有第二个示例可以正常工作。我不知道为什么第一个示例不更改原始数组但第二个示例更改。哪里不一样了?

第一个样本:

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

打印:

[4, 3, 5, 1]

第二个样本:

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

打印:

[1, 3, 4, 5]

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

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]

供您参考,阅读 How do I pass a variable by reference? 将帮助您了解引用在 Python 中的工作原理。

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

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

因此,您实际上是在更新原始 tab 对象,而不是将名称 tab 重新分配给新对象。

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

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]