您的位置:首页 > 编程语言 > Python开发

python 递归保存数据在list中不正确

2016-07-27 08:41 288 查看
这里使用python来求一个组合数

def combine(l_date, n, m, l_output, result):
for i in range(n, m - 1, -1):
l_output[m - 1] = l_date[i - 1]
if m > 1:
combine(l_date, i - 1, m - 1, l_output, result)
else:
print l_output
result.append(l_output)

result = []
l_output = [0]*2
list_date = [0, 1, 2]
combine(list_date, 3, 2, l_output, result)
print result


输出结果,与加入list的数据不一样

[1, 2]
[0, 2]
[0, 1]
[[0, 1], [0, 1], [0, 1]]
将程序改成这样
def combine(l_date, n, m, l_output, result):
for i in range(n, m - 1, -1):
l_output[m - 1] = l_date[i - 1]
if m > 1:
combine(l_date, i - 1, m - 1, l_output, result)
else:
print l_output
res = l_output[:]
result.append(res)

result = []
l_output = [0]*2
list_date = [0, 1, 2]
combine(list_date, 3, 2, l_output, result)
print result
输出结果变成正确的
[1, 2]
[0, 2]
[0, 1]
[[1, 2], [0, 2], [0, 1]]


原因分析:
递归的时候变量都保存在栈里,result里面存的是l_output的地址。但是,当递归函数运行结束,l_output就被pop掉了。

[]是引用 传址调用
[:] 是复制 穿值调用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: