Python:复杂的可迭代对象
Python: Complicated iterables
我看过这段代码,它遍历 class 的某些成员(如果存在的话)。值得注意的是,在二叉树中,遍历子项直到没有子项为止。
二叉树定义为..
# 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]
我不确定他们是如何想出那条线来遍历左右节点的,我永远不会当场想出它...我将如何剖析这条线?
阅读如下:
for node in level_list:
for child in (node.left, node.right):
if child:
child
如果我没记错的话,这个语句是创建列表的 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]
这基本上是 shorthand 执行以下几行的方法:
for node in level_list:
for child in (node.left, node.right):
if child:
level_list.append(child)
理解此 shorthand 语句的诀窍是查看外围边界符号,在本例中为 [
和 ]
。与 python 中的列表序列标识。由于列表中有迭代器(for
循环),我们基本上是在上述列表中创建或添加元素(变量 child
)。
/ogs
我看过这段代码,它遍历 class 的某些成员(如果存在的话)。值得注意的是,在二叉树中,遍历子项直到没有子项为止。
二叉树定义为..
# 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]
我不确定他们是如何想出那条线来遍历左右节点的,我永远不会当场想出它...我将如何剖析这条线?
阅读如下:
for node in level_list:
for child in (node.left, node.right):
if child:
child
如果我没记错的话,这个语句是创建列表的 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]
这基本上是 shorthand 执行以下几行的方法:
for node in level_list:
for child in (node.left, node.right):
if child:
level_list.append(child)
理解此 shorthand 语句的诀窍是查看外围边界符号,在本例中为 [
和 ]
。与 python 中的列表序列标识。由于列表中有迭代器(for
循环),我们基本上是在上述列表中创建或添加元素(变量 child
)。
/ogs