def divide(alist):
# when the list have only one element, it should return the 0
if len(alist) == 1:
alist[:] = list([0])
else:
middle = len(alist) / 2
divide(alist[:middle])
divide(alist[middle:])
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print temp
在我的函数中,递归之后,我想得到[0, 0, 0, 0, 0, 0]
,但是temp
仍然是[1,2,3,4,5,6]
。我还使用 alist[:] = list([0])
来确保重新分配 alist。
最佳答案
您的代码不起作用,因为 slicing
如 divide(alist[:middle])
中创建了一个新列表,因此 alist
之后第一个递归不再引用 temp
。
更常见的是返回
结果,而不是尝试在调用参数中创建副作用,例如:
def divide(alist):
# when the list have only one element, it should return the 0
if len(alist) == 1:
return [0]
middle = len(alist) // 2
return divide(alist[:middle]) + divide(alist[middle:])
print(divide(temp))
# [0, 0, 0, 0, 0, 0]
显然,这是相对无意义的,但我假设您只是设置结构来执行特定的操作。
如果您确实想这样做有副作用(不推荐!!!),那么您需要保留 left
和 right
索引并最终使用它分配[0]
,例如:
def divide(alist, left, right):
middle = (right - left) // 2
# when the list have only one element, it should return the 0
if middle == 0:
alist[left:right] = [0]
else:
divide(alist, left, left+middle)
divide(alist, left+middle, right)
temp = [1, 2, 3, 4, 5, 6]
divide(temp, 0, len(temp))
print(temp)
# [0, 0, 0, 0, 0, 0]
如果您想保留原始调用签名,那么您可以使用 _inner()
函数来处理递归,这将允许您默认参数,但实际上您可以只是 return _inner(0, len(alist))
没有它们:
def divide(alist):
def _inner(left=0, right=len(alist)): # default args based on comment @EricDuminil
middle = (right - left) // 2
# when the list have only one element, it should return the 0
if middle == 0:
alist[left:right] = [0]
else:
_inner(left, left+middle)
_inner(left+middle, right)
return _inner()
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print(temp)
# [0, 0, 0, 0, 0, 0]
关于python - 改变递归函数中列表对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354498/