簡體   English   中英

在元組Python中查找索引

[英]Finding the index in a tuple Python

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

您需要遞歸遍歷元組(如樹):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM