[英]Get the index of an element in a tuple of tuples
这与许多类似的问题有关,例如
但是,我不仅想检查它是否存在,还想检查它在哪个元组中,例如。 索引。 数据结构(来自 3rd 方库)始终是元组的元组。 (它不能嵌套更深)。
我想要作为返回值的是元素所在的元组的索引。我知道我可以肯定地将它与 for 循环一起破解,但是有没有更好的方法来获取索引?
您可以使用next和enumerate内置函数来获取索引。 您可以通过以下方式使用它:
def get_index_of_containing_tuple(lst: tuple, item):
try:
return next(ind for ind, tup in enumerate(lst) if item in tup)
except Exception:
return -1
使用它的例子:
a = (('a', 'b'), ('c', 'd'))
get_index_of_containing_tuple(a, 'a') # returns 0
get_index_of_containing_tuple(a, 'c') # returns 1
get_index_of_containing_tuple(a, 'd') # returns 1
get_index_of_containing_tuple(a, 123) # returns -1
这是一个没有for
循环的解决方案。 包含外部元组a
中查询元素的内部元组的索引作为列表返回
list(filter(lambda x: x != -1, map(lambda enum: enum[0] if 'queried_element' in enum[1] else -1, enumerate(a)))
对于嵌套元组中的重复元组元素,您可以使用单个 for 循环轻松管理。
example = (('apple','orange'),('orange','banana'),('banana','mango'))
def element_index(iterable, key = None):
index = set()
index_add = index.add
for ix, element in enumerate(iterable):
if key in element:
index_add(ix)
return index
nth_tuple(example, key = 'orange')
>> {0, 1}
index
方法类似地查看每个元素,直到第一次找到到达。 我认为 for 循环只要满足您的需要并且嵌套元组不是那么大就可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.