编辑:请参阅下面的建议答案以及它是如何还不完全正确的。
Stack Overflow 上有很多与此类似的问题,但没有一个与 Python 中的完全一样。我是一个编程新手,所以请放轻松。
我有一棵嵌套字典树,如下所示:
[{'word': 'The',
'next': [{'word': 'End',
'next': None},
{'word': 'quick',
'next': [{'word': 'brown',
'next': [{'word': 'fox',
'next': None}]}]},
{'word': 'best',
'next': [{'word': 'of',
'next': [{'word': 'times',
'next': None}]}]}]}]
我想从上到下展平所有路径并最终得到这个:
[[{'word': 'The'},
{'word': 'End'}],
[{'word': 'The'},
{'word': 'quick'},
{'word': 'brown'},
{'word': 'fox'}],
[{'word': 'The'},
{'word': 'best'},
{'word': 'of'},
{'word': 'times'}]]
我做了一个可爱的小递归函数,它首先创建了原始结构,但我很难取消递归它。据我所知:
def flatten_combinations(result_tree, current_combo = None, all_combos = None):
if current_combo is None:
current_combo = []
if all_combos is None:
all_combos = []
if result_tree is None:
all_combos.append(current_combo)
return
for word in result_tree:
current_combo.append({'word': word['word']})
flatten_combinations(word['next'], current_combo, all_combos)
return current_combo
…返回这个:
[{'word': 'The'},
{'word': 'End'},
{'word': 'quick'},
{'word': 'brown'},
{'word': 'fox'},
{'word': 'best'},
{'word': 'of'},
{'word': 'times'}]
…这显然有点接近,但并不完全正确。
我知道这个函数可能非常不符合 Python 风格,但我正在自学编程,所以我什至没有尝试利用可能存在的语言特性,这些特性会让我从头开始思考这些东西(”他说,张贴到一个问答网站,希望它的成员能帮助他消除一点想法)。
所以:我做错了什么?
编辑:下面的 Moshe 纠正了几个问题:
def flatten_combinations(result_tree, current_combo = None, all_combos = None):
if current_combo is None:
current_combo = []
if all_combos is None:
all_combos = []
if result_tree is None:
all_combos.append(current_combo)
return
for word in result_tree:
current_combo = current_combo[:]
current_combo.append({'word': word['word']})
flatten_combinations(word['next'], current_combo, all_combos)
return all_combos
这更接近了,但并不完全正确:
[{'word': 'The'},
{'word': 'End'}],
[{'word': 'The'},
{'word': 'End'},
{'word': 'quick'},
{'word': 'brown'},
{'word': 'fox'}],
[{'word': 'The'},
{'word': 'End'},
{'word': 'quick'},
{'word': 'best'},
{'word': 'of'},
{'word': 'times'}]]