我有一个python 父指针树列表,其中list的索引表示节点索引,并且列表中的父索引具有相应的值:
#1 2 3 4 5 6 7 8 9 10 11 12 13 14
parents = [2, 3, 13, 5, 12, 7, 11, 9, 10, 11, 12, 13, 14, 0]
我还有另一个列表,表明父母的元素是一片叶子:
#1 2 3 4 5 6 7 8 9 10 11 12 13 14
leaves_idx = [True, False, False, True, False, True, False, True, False, False, False, False, False, False]
现在我想重新映射父列表,使得前4个元素是叶子并保持树的结构:
remapped_parents = [6, 5, 7, 9, 12, 8, 11, 13, 10, 11, 12, 13, 14, 0]
#1 2 3 4 5 6 7 8 9 10 11 12 13 14
leaves_idx = [True, True, True, True, False, False, False, False, False, False, False, False, False, False]
有办法吗?
答案 0 :(得分:0)
所以基本上你想过滤掉前面的叶子和最后的非叶子节点。
parents = [2, 3, 13, 5, 12, 7, 11, 9, 10, 11, 12, 13, 14, 0]
leaves_idx = [True, False, False, True, False, True, False, True, False, False, False, False, False, False]
leaves = []
non_leaves = []
for i,j in enumerate (leaves_idx):
if j==True:
leaves.append(parents [i]) #leaves nodes at front
else:
non_leaves.append(parents [i]) #non leaves at last
final_list = leaves + non_leaves
这里将叶子和非叶子分成两个列表并在之后结束。