不懂就问, Python 中递归对 List 进行 append 的一个问题

2022-01-23 21:41:05 +08:00
 royrs

代码如下:

def QuanPaiLie(n):
    if n < l:
        for i in range(l):
            if plList[i] == 0:
                plList[i] = numsList[n]
                QuanPaiLie(n + 1)
                plList[i] = 0
    else:
        qplList.append(plList)

if __name__ == '__main__':
    numsList = [1, 2, 3]
    l = len(numsList)
    qplList = []
    plList = [0 for i in range(l)]
    
    QuanPaiLie(0)
    print(qplList)

运行后输出的结果是:

[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

而如果将qplList.append(plList)改为qplList.append(str(plList)),却可以输出:

['[1, 2, 3]', '[1, 3, 2]', '[2, 1, 3]', '[3, 1, 2]', '[2, 3, 1]', '[3, 2, 1]']

且不论算法的优劣,仅这个现象该如何解释呢。

请大佬赐教。

1278 次点击
所在节点    问与答
6 条回复
kidlj
2022-01-23 21:55:34 +08:00
没细看,应该是 Python 二维列表常见的一个错误用法,看一下我之前写的这篇文章是否对得上。


https://github.com/kidlj/site/blob/9aab72decaf58618dcd726110c0a30de6fb7f92b/_posts/2014-11-25-python-init.mkd
rabbbit
2022-01-23 21:56:34 +08:00
qplList.append(plList) 改成 qplList.append(plList[:])

为什么的话搜: python 可变 不可变对象
ipwx
2022-01-23 22:28:58 +08:00
。。因为列表是引用。

你无数次添加了同一个列表进去
Nitroethane
2022-01-23 22:48:29 +08:00
list 对象的 append 方法是 append 一个对象到列表中。因为 plList 是 list 对象,所以 append 进去是 [0,0,0] 这种。str() 是内建函数,作用是:当传递给 str() 函数的对象有 __str__() 方法时调用 __str__() 方法,否则调用 repr() 函数。https://docs.python.org/3/library/stdtypes.html#str
silentsee
2022-01-24 11:32:54 +08:00
print(qplList)是在所有递归都结束的时候,而 append(plList)中 plList 是引用,递归结束时已经被你置为 0 了,而 append(str(plList))中的 str(plList)是在递归最深处求值的,即使到了递归结束,因为 str 是不可变对象,所以 print 出了求值时候的值
royrs
2022-01-24 12:15:04 +08:00
感谢大家的回复,我慢慢看看。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/830134

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX