python 递归保存数据在list中不正确
2016-07-27 08:41
288 查看
这里使用python来求一个组合数
输出结果,与加入list的数据不一样
原因分析:
递归的时候变量都保存在栈里,result里面存的是l_output的地址。但是,当递归函数运行结束,l_output就被pop掉了。
[]是引用 传址调用
[:] 是复制 穿值调用
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掉了。
[]是引用 传址调用
[:] 是复制 穿值调用
相关文章推荐
- python工具(2) — 文件名检测
- leetcode 98 Validate Binary Search Tree (python)
- windows下面安装Python和pip终极教程
- python 导出hive数据表的schema
- python 设置运行进程的CPU
- python学习之路-12
- python工具(1) — 图片的位深度压缩
- python读取raw binary图片并提取统计信息
- Python 资源大全
- Python [Leetcode 350]Intersection of Two Arrays II
- python中package机制的两种实现方式
- Python入门笔记(5)_ 切片与迭代
- Python的并发编程
- python(四) 求两数的GCD(最大公约数)
- 各种 Python 库/模块/工具
- python的内存管理机制
- Python特殊用法[map、reduce、filter、lambda、列表推导式等]
- python2.6升级到3.3.0 的操作记录
- python模块之pexpect
- 深入理解Python装饰器