简体   繁体   English

Python:使用所有先前的索引和每个索引遍历列表

[英]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. 给定一个列表n长,如['animal', 'dog', 'golden retriever']['food', 'dinner', 'pasta', 'white sauce', 'fetucci alfredo']我需要遍历数组并获取当前索引,再加上每个先前的索引。

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. 也就是说, stuff['food']['dinner']可能存在,但我可能仍需要在晚餐中添加面食,在面食中添加白汁等。

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. 因此,在循环的每个“步骤”中, lst[:i+1]是您的“具有所有先前索引的当前索引”,并且您可以使用它进行任何操作。

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': {}}}} tree{'animal': {'dog': {'golden retriever': {}}}}

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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