This function will return a list containing the indices needed to reach an item in embedded sequences.
So deepindex([[1,2],[3,[4,[5,6]]],7,[8,9]],6) will return [1,1,1,1].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from __future__ import nested_scopes
import types
found='found'
def deepindex(sequence, goal):
"""deepindex(sequence,goal) -> index list"""
def helper(sequence,index_list):
for item in sequence:
if item==goal:
index_list.append(sequence.index(item))
raise found,index_list
elif isinstance(item,types.ListType) or isinstance(item,types.TupleType):
index_list.append(sequence.index(item))
index_list=helper(item,index_list)
else: return index_list[:-1]
try: helper(sequence,[])
except found,index_list: return index_list
else: return -1
|
This is handy for when you have very deep sequences and you need something better than list.index(item). It also, obviously, functions as a way to find out if something is in a deep sequence, regardless of whether you need to know its location within the sequence.