递归引用自身中的列表

递归引用自身中的列表

本文介绍了递归引用自身中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了一些非常奇怪的python内容.我尝试将对列表的引用添加到自身.该代码可能有助于证明我的发言要比我能表达的要好.我正在使用IDLE编辑器(交互模式).

So I came across something very weird in python. I tried adding a reference to the list to itself. The code might help demonstrate what I am saying better than I can express. I am using IDLE editor(interactive mode).

>>>l=[1,2,3]
>>>l.append(l)
>>>print(l)
[1,2,3,[...]]
>>>del l[:-1]
>>>print(l)
[[...]]

到目前为止,输出是预期的.但是当我这样做时.

So far the output is as expected. But when I do this.

y=l[:]
print(y)

在我看来,输出应该是

[[...]]

但是是

[[[...]]]

显然,它没有创建列表的副本,而是在y中放置了对该列表的引用.

Apparently instead of creating a copy of the list, it puts a reference to the list in y.

y [0]为l 返回True.我对此似乎找不到很好的解释.有什么想法吗?

y[0] is l returns True. I can't seem to find a good explanation for this. Any ideas?

推荐答案

不同之处仅在于列表的显示方式. IE. y的值正是您所期望的.

The difference is only in the way the list is displayed. I.e. the value of y is exactly what you'd expect.

列表显示方式的差异是由于与l不同,y不是自引用列表的事实.

The difference in the way the lists are displayed results from the fact that, unlike l, y is not a self-referencing list:

l[0] is l
=> True
y[0] is y
=> False

y不是自引用的,因为y不引用y.它引用l,这是自引用.

y is not self-referencing, because y does not reference y. It references l, which is self-referencing.

因此,将列表转换为字符串的逻辑检测到在y上工作的潜在无限递归要比在l上进行的更深一层.

Therefor, the logic which translates the list to a string detects the potential infinite-recursion one level deeper when working on y, than on l.

这篇关于递归引用自身中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:35