繁体   English   中英

这个python“for”复合语句是如何工作的?

[英]how does this python "for" compound statement work?

在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM