Skip to main content
 首页 » 编程设计

python之这个 python "for"复合语句是如何工作的

2025年05月04日10lori

我看到了 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