遞歸多位置索引:
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)]
可能在每個元組中(頂級「RECIPES」中的數量和平均多少種成分)? – dbr
我猜這個位置是'1,0'? –
你的意思是嵌套到任何深度?你的例子是一個扁平的列表 - 如果你想要一個解決方案來處理它,你應該爲嵌套食譜提供一個數據結構和期望的返回值。 – Dave