递归多位置索引:
import sys
from collections import Sequence,defaultdict
#making code python3-compatible
if sys.version_info[0] == 3:
basestring = str
def buildLocator(tree):
locator = defaultdict(list)
def fillLocator(tree, locator,location):
for index,item in enumerate(tree):
if isinstance(item,basestring):
locator[item].append(location+(index,))
elif isinstance(item,Sequence):
fillLocator(item,locator, location+(index,))
fillLocator(tree,locator,())
return locator
RECIPES = (
('apple', 'sugar', 'extreme_Force'),
('banana', 'syrup', 'magical_ends'),
('caramel', 'chocolate', 'pancake_MONSTER'),
('banana',('someAnother','banana'))
)
locator = buildLocator(RECIPES)
print(locator['banana'])
印刷
[(1, 0), (3, 0), (3, 1, 1)]