简体   繁体   中英

Finding the index in a tuple Python

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

how to get the positions: (binary tree)

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

is there any way to 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

You need to traverse the tuple recursively (like tree):

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

Usage:

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

BTW, don't use tuple as a variable name. It shadows builtin type/function tuple .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM