在元组Python中查找索引

时间:2014-10-11 13:42:03

标签: python list tuples

tuple = ('e', (('f', ('a', 'b')), ('c', 'd')))

如何获得职位:(二叉树)

[('e', '0'), ('f', '100'), ('a', '1010'), ('b', '1011' ), ('c', '110'), ('d', '111')]

有什么方法可以indexOf?

arvore[0] # = e
arvore[1][0][0] # = f
arvore[1][0][1][0] # = a
arvore[1][0][1][1] # = b
arvore[1][1][0] # = c
arvore[1][1][1] # = d

1 个答案:

答案 0 :(得分:5)

你需要递归遍历元组(如树):

def traverse(t, trail=''):
    if isinstance(t, str):
        yield t, trail
        return
    for i, subtree in enumerate(t):  # left - 0, right - 1
        # yield from traverse(subtree, trail + str(i))   in Python 3.3+
        for x in traverse(subtree, trail + str(i)):
            yield x

用法:

>>> t = ('e', (('f', ('a', 'b')), ('c', 'd')))
>>> list(traverse(t))
[('e', '0'), ('f', '100'), ('a', '1010'), ('b', '1011'), ('c', '110'), ('d', '111')]

顺便说一句,不要使用tuple作为变量名。它影响内置类型/功能tuple