【问题标题】:Python: Complicated iterablesPython:复杂的迭代
【发布时间】:2019-02-20 21:55:24
【问题描述】:

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

二叉树定义为..

# 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


    【解决方案1】:

    如果我没记错的话,这个语句是一种创建列表的pythonic和简写方式。

     # 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

    【讨论】:

    • 两者在运行时有区别吗?简洁的速记方式是更快(和/或推荐的做法)还是真的没有区别?
    • 没有运行时差异。然而,许多人这样做是为了节省代码行数。如果我正在代码冲刺,我也会专门这样做。
    • @Ogs 不是真的,很难阅读和调试。所以最好的做法是避免这种编码模式
    • @Kalanamith 是的。但没有运行时差异。呵呵。从美学上讲 - 我同意你的观点,很难阅读和调试......
    【解决方案2】:

    如下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多