我有一个b*列树*其中叶只有字符串值 (a,b,c,d,e),我希望c*对这些叶子的值进行连接,并将它传递给它们的祖先*。
0
/ \
2 3
/ \ / \
1 a d e
/ \
b c例如:
1->value=bc 2->value=abc 3->value=de 在python ete2树类中最好的方法是什么?
提前感谢
发布于 2013-08-20 07:57:22
一个非常标准的过程是使用postorder迭代。此外,埃特还实现了get_cached_content函数,它简化了这种类型的计算。
from ete2 import Tree
t = Tree("(((b,c), a), (d,e));")
print "Method 1: caching node content"
internal_node_content = t.get_cached_content(store_attr="name")
for node, content in internal_node_content.iteritems():
if not node.is_leaf():
print node, "\nConcat:", ''.join(content)
print "Method 2: post order iteration"
node2concat = {}
for node in t.traverse("postorder"):
if not node.is_leaf():
concat = ''.join([node2concat[ch] for ch in node.children])
node2concat[node] = concat
print node, "\nConcat:", concat
else:
node2concat[node] = node.name
#Method 1: caching node content
#
# /-b
# /-|
# /-| \-c
# | |
#--| \-a
# |
# | /-d
# \-|
# \-e
#Concat: acbed
#
# /-b
#--|
# \-c
#Concat: cb
#
# /-b
# /-|
#--| \-c
# |
# \-a
#Concat: acb
#
# /-d
#--|
# \-e
#Concat: ed
#Method 2: post order iteration
#
# /-b
#--|
# \-c
#Concat: bc
#
# /-b
# /-|
#--| \-c
# |
# \-a
#Concat: bca
#
# /-d
#--|
# \-e
#Concat: de
#
# /-b
# /-|
# /-| \-c
# | |
#--| \-a
# |
# | /-d
# \-|
# \-e
#Concat: bcadehttps://stackoverflow.com/questions/18317932
复制相似问题