无法在python 3中迭代列表类型

无法在python 3中迭代列表类型,python,list,loops,Python,List,Loops,问题: root.children(在下面的代码中命名)是一个列表类型,但我仍然无法迭代每个项目,有人知道原因吗?谢谢 我的代码: class Node(): def __init__(self, value) -> object: self.value = value self.children = [] def __repr__(self, level=0): ret = "\t"*level+repr

问题:

root.children
(在下面的代码中命名)是一个
列表
类型,但我仍然无法迭代每个项目,有人知道原因吗?谢谢

我的代码:

class Node():
    def __init__(self, value) -> object:
        self.value = value
        self.children = []
    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret
    def add_child(self, node):
        self.children.append(node)
    def __iter__(self):
        return iter(self.children)
    

list_1 = ['Lisa', 'apple', 'banana']   #, 'orange', 'Kiwi'
root = parent = Node(list_1[0])
i=1
while i < len(list_1):
    current_node = Node(list_1[i])
    parent.add_child(current_node)
    parent = current_node
    j=0
    while j < len(root.children): # root.children is a list type, but I still cannot iterate each item in the list
        print('YES')
        j+=1
    i+=1
print(root)
期望输出:

YES
YES
'Lisa'
    'apple'
        'banana'

YES
YES
YES
YES
YES
'Lisa'
    'apple'
        'banana'

我的目的实际上是搜索当前“root.children”中的所有项目,如果我的目标项目已经存在于“root.children”中,那么我将“做点什么”。

您的代码对于所需的输出不正确。您希望第二个while循环的运行次数与root的子循环的运行次数相同。但在每次迭代中,root只有一个子元素。所有其他的亚孩子都是根的孩子、独生子女等等

循环结束后,这就是实例根的样子

root(
val = "Lisa"
children = [(val="apple",
            children=[(val="banana",children=[])]
           ]
)
我希望这能让你明白一点。因为root总是只有一个子元素。每次运行外部循环时,内部循环只运行一次(在您的情况下为2),因此“是”只打印两次


要修复代码并获得所需的输出,您可以修改代码并递归调用它,而不是使用循环。在每次递归调用中,root的子节点成为root,函数将被再次调用,直到达到基本情况,这将是一个没有子节点的节点

这将是什么
root=parent=Node(list_1[0])
您尝试过一些吗。您可以观察它的行为偏离预期行为的地方。然后从那里向后工作以确定问题的原因。@Pranav,我已经调试并检查了每个变量的值,但我只看到当涉及到root.children时,for循环不能很好地工作,它只发生一次,在root.children列表中的每个项的末尾都有\n,我不知道为什么,这就是为什么我在这里发帖的原因。你这样做的原因是
,而
循环而不是
列表中的名称:
?@Melina“我有很多原因”,从我们在这里看到的,你有很多不好的原因。研究Barmar提出的印刷品,并纠正你的程序结构。如果你不知道你想要实现什么,就很难给你结构上的反馈。谢谢Dhwani,你已经完全理解并描述了我想要实现的东西。根据您的建议,我正在尝试递归:)