列表以嵌套树中的错误格式返回到列表列表转换

时间:2014-12-27 11:26:12

标签: python python-2.7 tree iterator

我正在尝试编写函数来在列表格式列表和嵌套字典格式之间移动树结构。这两个函数(paths2treetree2paths)在下面的代码中给出。从列表列表到嵌套树(paths2tree函数)的转换工作正常,但反向转换(tree2paths构建为迭代器)无法生成正确的列表。

最后一小段代码测试这两个函数。在tree2paths转换中,print语句建议函数生成正确的列表,但yield语句似乎不会将该信息返回给调用语句。 tree2paths函数返回正确的列表,但格式不正确。

知道为什么yield语句没有返回可用列表?

def paths2tree(paths):
    tree = {}
    for path in paths:
        current_level = tree
        for part in path:
            if part not in current_level:
                current_level[part] = {}
            current_level = current_level[part]     
    return tree


def tree2paths(tree,base=None):
        for branch in tree.keys() : 
            if base is None:
                subbase = [branch]
            else:
                subbase = base+[branch]
            yield subbase
            print subbase
            newbase = list(tree2paths(tree[branch],subbase))
            yield newbase
paths = [['root','boot','bah'],
         ['root','boot'],
         ['root','boot','bad'],
         ['root'],
         ['root','toot'],
         ['root','toot','tah'],
         ['root','toot','tad'],
         ['root','toot','tad','two']
         ]

atree = paths2tree(paths)    
print atree    
newpaths = list(tree2paths(atree))
print newpaths

1 个答案:

答案 0 :(得分:1)

问题在于:

newbase = list(tree2paths(tree[branch],subbase))
yield newbase

问题是list(tree2paths(tree[branch],subbase))是包含路径的列表列表。当您只是产生该列表时,您会在newbase列表['root'][['root', 'toot'], ..., ['root', 'boot', 'bah'], []]]中获得两个元素。你需要做的是迭代newbase,并产生每个元素:

def tree2paths(tree,base=None):
  for branch in tree.keys() : 
        if base is None:
            subbase = [branch]
        else:
            subbase = base+[branch]
        yield subbase
        print subbase
        newbase = list(tree2paths(tree[branch],subbase))
        for i in newbase:
            yield i

这产生了预期的结果:

['root']
['root', 'toot']
['root', 'toot', 'tad']
['root', 'toot', 'tad', 'two']
['root', 'toot', 'tah']
['root', 'boot']
['root', 'boot', 'bad']
['root', 'boot', 'bah']

请注意,在Python 3.3中,您只需编写yield from tree2paths(tree[branch],subbase)