构建系统发育树

Bio*_*eek 5 python tree bioinformatics phylogeny

我有一个像这样的列表列表

matches = [[['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', 'Firmicutes'], ['class', 'Clostridia'], ['order', 'Clostridiales'], ['family', 'Lachnospiraceae'], ['genus', 'Lachnospira']], 
           [['rootrank', 'Root'], ['domain', 'Bacteria'], ['phylum', '"Proteobacteria"'], ['class', 'Gammaproteobacteria'], ['order', '"Vibrionales"'], ['family', 'Vibrionaceae'], ['genus', 'Catenococcus']], 
           [['rootrank', 'Root'], ['domain', 'Archaea'], ['phylum', '"Euryarchaeota"'], ['class', '"Methanomicrobia"'], ['order', 'Methanomicrobiales'], ['family', 'Methanomicrobiaceae'], ['genus', 'Methanoplanus']]]
Run Code Online (Sandbox Code Playgroud)

我想从它们构建系统发育树。我写了一个像这样的节点类(部分基于此代码):

class Node(object):
    """Generic n-ary tree node object
    Children are additive; no provision for deleting them."""

    def __init__(self, parent, category=None, name=None):
        self.parent = parent
        self.category = category
        self.name = name
        self.childList = []

        if  parent is None:
            self.birthOrder  =  0
        else:
            self.birthOrder  =  len(parent.childList)
            parent.childList.append(self)

    def fullPath(self):
        """Returns a list of children from root to self"""
        result  =  []
        parent  =  self.parent
        kid     =  self

        while parent:
            result.insert(0, kid)
            parent, kid  =  parent.parent, parent

        return result

    def ID(self):
        return '{0}|{1}'.format(self.category, self.name)
Run Code Online (Sandbox Code Playgroud)

然后我尝试像这样构建我的树:

node = None
for match in matches:
    for branch in match:
        category, name = branch
        node = Node(node, category, name)
        print [n.ID() for n in node.fullPath()]
Run Code Online (Sandbox Code Playgroud)

这适用于第一场比赛,但是当我从第二场比赛开始时,它会附加到树的末尾,而不是从顶部再次开始。我该怎么做?我在搜索 ID 时尝试了一些变体,但无法正常工作。

mr2*_*ert 2

问题是它node始终是树中最底部的节点,并且您总是附加到该节点。您需要存储根节点。由于['rootrank', 'Root']出现在每个列表的开头,我建议将其取出并将其用作根。所以你可以这样做:

rootnode = Node(None, 'rootrank', 'Root')
for match in matches:
    node = rootnode
    for branch in match:
        category, name = branch
        node = Node(node, category, name)
        print [n.ID() for n in node.fullPath()]
Run Code Online (Sandbox Code Playgroud)

这将使matches列表更具可读性,并给出预期的输出。