【发布时间】:2017-02-22 10:40:22
【问题描述】:
def insertionSort(lst):
#create variable to store final sorted list
sortedLst = []
#add any number into the list so the program can start inserting
sortedLst.append(lst.pop())
#for each item left over in the original list compare to sorted list
for sortInd in range(len(lst)-1,-1,-1):
#for each index to sort
for sortingInd in range(len(sortedLst),-1,-1):
if sortingInd == 0 or sortingInd == len(sortedLst):
sortedLst.insert(sortingInd,lst.pop())
break
if lst[sortInd] > sortedLst[sortingInd]:
sortedLst.insert(sortingInd,lst.pop())
break
print(sortedLst) #gives [1,2,3]
print(lst) #gives []
lst = sortedLst
print(lst) #gives [1,2,3]
lst = [3,2,1]
insertionSort(lst)
#lst should be [1,2,3] yet gives []
print(lst)
我正在尝试编写一个插入排序,插入排序本身确实可以工作,但是因为这是我编写的更多排序的一部分,我特别不想在函数外部为排序列表声明一个新变量并拥有函数返回一个排序列表以与我的其他函数保持一致。例如我不想要:
lst = [3,2,1]
newLst = insertionSort(lst)
相反,我希望 insertSort 函数更改我原来的 lst 变量,当我弹出要排序的值时它确实会改变,但在函数结束之前将其设置为 sortedLst 时它不会改变。
提前感谢您的任何回答:)。
【问题讨论】:
-
Python 有很好的文档,这应该在execution model 部分解释。例如,函数内部的
lst不是函数外部的lst,并且lst = x不会复制x。 -
嗯,我明白这一点,为什么我的 lst 不会在我执行 'lst = sortedLst' 时更改为我的 sortedLst 但为什么 lst.pop() 实际上会从我的lst 在函数之外,而不仅仅是在函数内部?谢谢
-
你知道名字、引用(指针)和值的区别吗?
-
我很确定,引用指的是内存位置,值是存储在内存位置的东西,名称是对内存位置的引用的名称。如我错了请纠正我。我的问题现在已经在 Daniel Roseman 的答案中得到了回答。不过感谢您的帮助。
标签: python list python-3.x global-variables