简体   繁体   中英

Python: loop through a list using all previous indexes with each index

Given a list n long, such as ['animal', 'dog', 'golden retriever'] or ['food', 'dinner', 'pasta', 'white sauce', 'fetucci alfredo'] , I need to loop through the array and get the current index, plus each previous index.

Is there any good way to loop through and do this such that a list of any length can still be turned into:

stuff['food']
stuff['food']['dinner']
stuff['food']['dinner']['pasta']
stuff['food']['dinner']['pasta']['white sauce']
stuff['food']['dinner']['pasta']['white sauce']['fetucci alfredo']

I'm moving increasingly deeper into an object, but each value may or may not yet exist, so I need to stop at each level down. ie, stuff['food']['dinner'] may exist, but I may still need to add pasta to dinner, white sauce to pasta, etc.

This?

>>> lst = ['food', 'dinner', 'pasta', 'white sauce', 'fetucci alfredo']
>>> for i in range(len(lst)):
...   print lst[:i+1]
... 
['food']
['food', 'dinner']
['food', 'dinner', 'pasta']
['food', 'dinner', 'pasta', 'white sauce']
['food', 'dinner', 'pasta', 'white sauce', 'fetucci alfredo']

So at each "step" of the loop, lst[:i+1] is your "current index with all the previous indices" and you can do whatever you wish with it.

For example, you can use it to index into some deeply nested hierarchical dict:

d = mydict
for index in lst[:i+1]:
  d = d[index]

I think it is like a tree data structure

test = ['animal', 'dog', 'golden retriever']
tree = {}
subtree = tree
for x in test:
    subtree = subtree.setdefault(x, {})

the tree is {'animal': {'dog': {'golden retriever': {}}}}

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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