[英]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 ? 有什么办法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. 顺便说一句,不要使用tuple
作为变量名。 It shadows builtin type/function tuple
. 它隐藏了内置类型/函数tuple
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.