首页 > 解决方案 > 基本脚本的 Python 初学者问题

问题描述

我正在阅读 Python Complete 参考书,在练习中有一个问题说要添加以下内容:

    L=[1, 2]
    L.append(L)
    print (L)

作为回应,我得到这样的输出

    [1, 2, 3, [...]]

然而在书中它提到,直到你按下 break 键,它才会无限地追加列表:如下:一个 [1, 2, [1, 2, [1, 2, [1, 2, 等] 的无休止流开,直到您按下断键组合

有人可以解释我做错了什么吗?

标签: python-3.xscripting

解决方案


The program isn't actually infinitely appending the list (that would imply that the list length is equal to infinity, which it's not --- if you run len(L), you will see that the length is 3). Rather, it is infinitely recursing.

The list starts out with two elements, 1 and 2 (I take it you have a mistake in your output above where you show "3" being printed, since there is never a 3 added to the list).

You then tell the list you want the third element to be equal to the existing list. However, due to how python passes data, what you're essentially doing is storing a reference to list L. Something like this: [1, 2, ref(L)].

When you go to print the list then, the first two elements appear easily: 1, 2. However, for the third element, python says "let me go grab list L and show it." Okay, so what is list L? It is [1, 2, ref(L)]. Hm. So python says again, "okay, this third element is kind of tricky. I know it is a list of length 3, and I know what the first two elements are, but I need to go get the third element, which is list L. What is list L? ..." and on it goes.

The [...] is to indicate that the third element (L[2]) is never able to be fully defined because each ref(L) that is fetched contains within it another ref(L) element.

Thus your actual output is something like this:

=> [1, 2, ref(L)]
=> [1, 2, [1, 2, ref(L)]]
=> [1, 2, [1, 2, [1, 2, ref(L)]]]
=> [1, 2, [1, 2, [1, 2, [1, 2, ref(L)]]]]
...

which python helpfully truncates as [1, 2, [...]] to show that this pattern just repeats forever.


推荐阅读