python - 改变递归函数中列表对象的值

标签 python python-2.7

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。

为什么?引用有问题吗?

最佳答案

您的代码不起作用,因为 slicingdivide(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]

显然,这是相对无意义的,但我假设您只是设置结构来执行特定的操作。

如果您确实想这样做有副作用(不推荐!!!),那么您需要保留 leftright 索引并最终使用它分配[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/

相关文章:

python - 将变量从一个 python 脚本导入到另一个

Python - 解决空页面中 Beautifulsoup 的 "object has no attribute"错误

python - 字节字符串与 Unicode 字符串。 Python

python - 在 Python 中,如何创建从现在起 15 分钟后的日期时间? 1小时后?

Python 在遍历列表时找不到值

python-2.7 - 如何使用opencv python检测箭头?

python - 当javascript生成一些html时获取html源

python - 如何从 python 2.7 中将数据输入到命令提示符中

python - 修改字典项类型

python - pytesseract,Windows 错误 : [Error 2] The system cannot find the file specified