【问题标题】:Lists returned in wrong format in nested tree to list-of-lists conversion嵌套树中以错误格式返回的列表到列表转换
【发布时间】:2015-02-24 08:02:45
【问题描述】:

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

最后的一小段代码测试了这两个函数。在tree2paths 转换中,一个打印语句表明该函数正在生成正确的列表,但该 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

【问题讨论】:

    标签: python python-2.7 tree iterator


    【解决方案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)

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多