我看到了 a problem on leetcode 的以下解决方案:
class Solution:
def levelOrder(self, root):
"""
:type root: Node
:rtype: List[List[int]]
"""
if root is None:
return []
q, res = [root], []
q1 = []
while q:
res.append([node.val for node in q])
q = [child for node in q for child in node.children]
return res
[child for node in q for child in node.children]
如何工作? child 放在 for 循环语句之前是什么意思?
最佳答案
这是一个嵌套的列表理解。
q = [child for node in q for child in node.children]
相当于:
tmp = []
for node in q:
for child in node.children:
tmp.append(child)
q = tmp
关于python - 这个 python "for"复合语句是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54500076/