简体   繁体   English

Python:元组内部的元组获取子索引

[英]Python : tuple inside tuple get child index

i have this tuple: 我有这个元组:

STATUS = ((1, 'Standby'), (2, 'Approved'), (3, 'Rejected'))

The problem seems to be that this is a tuple (x,x,x) inside other tuple where x is (i,'string') . 问题似乎是这是另一个tuple (x,x,x)内部的tuple (x,x,x) ,其中x(i,'string') I need to get a index from the child tuple this is possible by doing this STATUS[0].index('Standby') 我需要从子元组获取索引,这可以通过执行STATUS[0].index('Standby')

but this is not a good solution because i can't find directly by name. 但这不是一个好的解决方案,因为我无法直接按名称查找。

So, i want to find the index directy without to mention what is the position of the tuple that i'm seeking. 因此,我想直接找到索引,而不要提及我要查找的元组的位置。

Why not use a list and then use index? 为什么不使用列表然后使用索引?

STATUS = [None, 'Standby', 'Approved', 'Rejected']
STATUS.index('Standby')

returns 1 返回1

Well, 好,

it seems that doesn't exist any solution by default. 似乎默认情况下不存在任何解决方案。 So you need to do a function. 因此,您需要执行一个功能。 Using the suggestion of @tobias_k i made this possible solution. 使用@tobias_k的建议,我提出了可能的解决方案。

def deepindex(mytuple,myvalue):
   for i in mytuple:
      if i.index(myvalue):
         return i.index(myvalue)

>>> deepindex(STATUS,'Standby')
>>> 1

Please if you find a better solution let me know. 如果您找到更好的解决方案,请告诉我。 Thanks ;) 谢谢 ;)

Zip and map seems to be a good approach 邮编和地图似乎是一个好方法

zip: aggregates elements from each of the iterables (*STATUS) (see docs ) zip:汇总每个可迭代对象(* STATUS)中的元素(请参阅docs

map: to every item of iterable and return a list of the results (see docs ) 映射:到iterable的每个项目,并返回结果列表(请参阅docs

Using this two functions: you can get the index of a tuple inside another tuple as is described on this question as STATUS. 使用这两个函数:您可以在另一个元组中获取一个元组的索引,如在此问题上描述为STATUS。

>>> a,b= map(list,zip(*STATUS))
>>> a[b.index('Standby')]
>>> 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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