[英]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.