gpt4 book ai didi

Python 2.7.3 |创建了一个列表并尝试将其附加到自身,这是我得到的结果,有人可以解释一下它发生了什么吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:41:22 25 4
gpt4 key购买 nike

我用 python 创建了一个列表,

 list1 = [1,2,3,4]

并尝试将其附加到本身,

 list1.append(list1)

这就是我所拥有的,它永无止境!有人可以解释一下发生了什么事吗?

 >>> list1=[1,2,3,4]
>>> list1.append(list1)
>>> list1
[1, 2, 3, 4, [...]]
>>> len(list1)
5
>>> len(list1[4])
5
>>> print list1[4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4][4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4][4][4][4][4]
[1, 2, 3, 4, [...]]
>>> print list1[4][4][4][4][4][4][4][4][4]
[1, 2, 3, 4, [...]]

这永无止境。谢谢您

最佳答案

Python 中的名称是指向对象的指针。在这种情况下

>>> lst = [1, 2, 3, 4]

您创建一个新的 list 对象,其中包含 4 个 int 值,并将其分配给名称 lst。下一页

>>> lst.append(lst)

您将一个新项目添加到列表末尾;指向列表本身的指针。这将创建循环引用,Python 将其打印为 [...]。这是因为lst中的最后一项指向lst,其中最后一项指向lst,其中...

如果要将列表的内容追加到列表中,则需要复制该对象,这可以通过切片来完成:

>>> lst.append(lst[:])
>>> lst
[1, 2, 3, 4, [1, 2, 3, 4]]

关于Python 2.7.3 |创建了一个列表并尝试将其附加到自身,这是我得到的结果,有人可以解释一下它发生了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20442180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com