Python:复杂的可迭代项

时间:2018-09-17 01:51:53

标签: python generator breadth-first-search iterable

我已经看过这段代码,它会迭代类的某些成员(如果存在)。值得注意的是,在二叉树中,遍历子节点直到没有更多子节点为止。

二叉树定义为..

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

他们这样迭代:

# type root : TreeNode
def iterateTree(self, root):
    level_list = [root]

    while level_list:

        for item in level_list:
             print(item.val)

        # This iterable seems really complicated for me to understand how they came up with this
        level_list = [child for node in level_list for child in (node.left, node.right) if child]

我不确定他们是如何想出这条线来遍历左右节点的,我永远不会当场想出……我将如何剖析这条线?

2 个答案:

答案 0 :(得分:2)

内容如下:

for node in level_list:
    for child in (node.left, node.right):
        if child:
            child

答案 1 :(得分:0)

如果我没记错的话,此声明是创建列表的一种Python快捷方式。

 # This iterable seems really complicated for me to understand how they came up with this
   level_list = [child for node in level_list for child in (node.left, node.right) if child]

这基本上是完成以下几行代码的简便方法:

for node in level_list:
    for child in (node.left, node.right):
        if child:
            level_list.append(child)

理解此速记语句的技巧是查看外围的边界符号,在这种情况下,它们是[]。它用python中的列表序列标识。由于列表中有迭代器(for循环),因此我们基本上是在所述列表中创建或添加元素(变量child)。

/ ogs