Python 在嵌套树到列表转换列表中以错误格式返回的列表
我正在尝试编写函数,以便在列表格式和嵌套字典格式之间移动树结构。下面的代码中给出了两个函数(Python 在嵌套树到列表转换列表中以错误格式返回的列表,python,python-2.7,tree,iterator,Python,Python 2.7,Tree,Iterator,我正在尝试编写函数,以便在列表格式和嵌套字典格式之间移动树结构。下面的代码中给出了两个函数(paths2tree和tree2paths)。从列表列表到嵌套树的转换(paths2tree函数)工作正常,但反向转换(tree2paths,构建为迭代器)无法生成正确的列表 最后一小段代码测试这两个函数。在tree2paths转换中,print语句表明函数正在生成正确的列表,但yield语句似乎没有将该信息返回给调用语句。tree2paths函数返回正确的列表,但格式不正确 知道收益率语句为什么不返回可
paths2tree
和tree2paths
)。从列表列表到嵌套树的转换(paths2tree
函数)工作正常,但反向转换(tree2paths
,构建为迭代器)无法生成正确的列表
最后一小段代码测试这两个函数。在tree2paths
转换中,print语句表明函数正在生成正确的列表,但yield语句似乎没有将该信息返回给调用语句。tree2paths函数返回正确的列表,但格式不正确
知道收益率语句为什么不返回可用列表吗
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
问题在于:
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']
请注意,在Python3.3中,您可以只编写从tree2path(tree[branch],subbase)生成