Python:复杂的迭代

问题描述 投票:1回答:2

我已经看到这段代码迭代了类的某些成员(如果它们存在)。值得注意的是,在二叉树中,迭代孩子,直到没有更多的孩子。

二叉树定义为..

# 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]

我不确定他们是如何想出那条线来迭代左右节点的,我当然不会想到那个......我怎么解剖这条线?

python generator breadth-first-search iterable
2个回答
2
投票

阅读如下:

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

0
投票

如果我没有弄错的话,这句话是一种创建列表的pythonic和short-hand方式。

 # 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)。

/还

© www.soinside.com 2019 - 2024. All rights reserved.