简体   繁体   English

获取元组元组中元素的索引

[英]Get the index of an element in a tuple of tuples

This is related to many similar questions like这与许多类似的问题有关,例如

Check if element exists in tuple of tuples 检查元组的元组中是否存在元素

However I do not only want to check it it exist but in which of the tuples it is in, eg.但是,我不仅想检查它是否存在,还想检查它在哪个元组中,例如。 the index.索引。 The data structures (from 3rd party library) is always a tuple of tuples.数据结构(来自 3rd 方库)始终是元组的元组。 (it can't be nested any deeper). (它不能嵌套更深)。

What I want as return value is the index of the tuple the element is located in. I know I can for sure hack this together with for loops but is there any nicer way to get the index?我想要作为返回值的是元素所在的元组的索引。我知道我可以肯定地将它与 for 循环一起破解,但是有没有更好的方法来获取索引?

you may use next and enumerate built-in functions to have a nice way of getting the index.您可以使用nextenumerate内置函数来获取索引。 You may use it the following way:您可以通过以下方式使用它:

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

Example of using it:使用它的例子:

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

Here's a solution without for loops.这是一个没有for循环的解决方案。 Indices of the inner tuples containing the queried element in the outer tuple a are returned as a list包含外部元组a中查询元素的内部元组的索引作为列表返回

list(filter(lambda x: x != -1, map(lambda enum: enum[0] if 'queried_element' in enum[1] else -1, enumerate(a)))

For repeating tuple elements within in the nested tuple, you can easily manage with a single for loop.对于嵌套元组中的重复元组元素,您可以使用单个 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}

The index method similarly looks into each element till reach first found. index方法类似地查看每个元素,直到第一次找到到达。 I think a for loop will work just fine as long it suits your needs and the nested tuple is not that large.我认为 for 循环只要满足您的需要并且嵌套元组不是那么大就可以正常工作。

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

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