Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用列表理解添加单独的元素_Python_.net_List Comprehension_Ironpython - Fatal编程技术网

Python 使用列表理解添加单独的元素

Python 使用列表理解添加单独的元素,python,.net,list-comprehension,ironpython,Python,.net,List Comprehension,Ironpython,我试图使用IronPython中的列表理解生成对象列表,以将其作为数组传递给函数。下面的代码生成一个TreeNode对象数组,例如[treeNode1,treeNode2,treeNode3]我想在数组中添加一个根节点,这样它可以像[treeNode1,treeNode2,treeNode3,root]那样扩展数组,而不是像[treeNode1,treeNode2,treeNode3],root] def _to_tree_nodes(self,lst): l=dict()

我试图使用IronPython中的列表理解生成对象列表,以将其作为数组传递给函数。下面的代码生成一个
TreeNode
对象数组,例如
[treeNode1,treeNode2,treeNode3]
我想在数组中添加一个根节点,这样它可以像
[treeNode1,treeNode2,treeNode3,root]
那样扩展数组,而不是像
[treeNode1,treeNode2,treeNode3],root]

def _to_tree_nodes(self,lst):
        l=dict()
        for tuple in lst:
            if tuple[1] not in l:
                l.update({tuple[1]:[tuple[0]]})
            else:
                l[tuple[1]].append(tuple[0])

        root = TreeNode("Level " + str(max(l)), Array[TreeNode]([TreeNode(x) for x in l[max(l)]]))
        for i in xrange(max(l)-1,0,-1):
            root = TreeNode("Level " + str(i), Array[TreeNode]([TreeNode(x) for x in l[i]]))

        return root

如何实现它?

只需连接一个额外的列表对象:

root = TreeNode("Level " + str(i), Array[TreeNode](
    [TreeNode(x) for x in l[i]] + [root]))