为什么附加列表本身会创建无限列表 [英] Why does appending a list by itself create an infinite list

查看:35
本文介绍了为什么附加列表本身会创建无限列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

l = [1, 2]
l.append(l)
>>>l
[1, 2, [...]] #l is an infinite list

为什么这样做会创建一个无限列表而不是创建:

Why does this create an infinite list instead of creating:

l = [1, 2]
l.append(l)
>>>l
[1, 2, [1, 2]]

推荐答案

当您这样做:

l.append(l)

列表 l 引用附加到列表 l 的列表:

a reference to list l is appended to list l:

>>> l = [1, 2]
>>> l.append(l)
>>> l is l[2]
True
>>>

换句话说,您将列表放在其内部.这将创建一个无限参考循环,该循环由 [...] 表示.

In other words, you put the list inside itself. This creates an infinite reference cycle which is represented by [...].

要执行所需的操作,您需要添加列表 l 副本:

To do what you want, you need to append a copy of list l:

>>> l = [1, 2]
>>> l.append(l[:])  # Could also do 'l.append(list(l))' or 'l.append(l.copy())'
>>> l
[1, 2, [1, 2]]
>>> l is l[2]
False
>>>

这篇关于为什么附加列表本身会创建无限列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆