gpt4 book ai didi

python - 令人困惑的 [...] Python 中的列表 : What is it?

转载 作者:IT老高 更新时间:2023-10-28 21:06:25 25 4
gpt4 key购买 nike

所以我在 Python 中编写了一个简单的二叉树,结果遇到了 [...]

我不认为这与 Ellipsis 对象有关,它似乎与无限循环有关(由于 Python 的浅拷贝?)。但是,这个无限循环的来源以及为什么在访问时扩展时它没有得到扩展是我完全不知道的



>>> 一个
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...] , [...], -4, [...], [...], 0, [...], [...]]
>>> 键(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...] , [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...] , [...], 0, [...], [...]]

使用 a+b 的版本

def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y

使用 [a,b] 的版本

def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y

那么 [...] 到底是什么?

最佳答案

如果您有一个带有指向自身的列表的循环结构,它也会出现。像这样:

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

由于 python 无法打印出结构(这将是一个无限循环),它使用省略号来表明结构中存在递归。


我不太确定问题是发生了什么或如何修复它,但我会尝试更正上述功能。

在这两种方法中,您首先进行两次递归调用,将数据添加到列表 y,然后再次将返回的数据附加到 y。这意味着相同的数据将在结果中出现多次。

要么只收集所有数据而不添加任何y,例如

return [x[2]]+keys(x[0])+keys(x[1])

或者只是在调用中进行附加,例如

y += [x[2]]
keys(x[0], y) #Add left children to y...
keys(x[1], y) #Add right children to y...
return y

(当然,这两个片段都需要处理空列表等)

@Abgan 还指出您确实不希望在初始化程序中使用 y=[]

关于python - 令人困惑的 [...] Python 中的列表 : What is it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/397034/

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