Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a generator that creates a flat list of indices into the list of lists:</p> <pre><code>def enumerate_nested(nested, indices): for i, item in enumerate(nested): if isinstance(item, collections.Iterable) and not isinstance(item, basestring): for new_indices in enumerate_nested(item, indices + (i,)): yield new_indices else: yield indices + (i,) </code></pre> <p>Then a simple function that extracts an innermost item from the list of lists based on an index tuple:</p> <pre><code>def tuple_index(nested_list, index_tuple): for i in index_tuple: nested_list = nested_list[i] return nested_list </code></pre> <p>Now all you have to do is traverse the flat index list, in whatever way you like.</p> <pre><code>&gt;&gt;&gt; indices = list(enumerate_nested(l, tuple())) &gt;&gt;&gt; print l [1, 2, 3, ['a', 'b', 'c'], 4, ['d', 'e', [100, 200, 300]], 5, ['a', 'b', 'c'], 6] &gt;&gt;&gt; for i in indices: ... print tuple_index(l, i), ... 1 2 3 a b c 4 d e 100 200 300 5 a b c 6 </code></pre> <hr> <p>Since this answer was accepted for the stack-based solution that I posted on ideone in the comments, and since it's preferable not to use external pastebins for answer code, please note that <a href="https://stackoverflow.com/questions/6558365/convert-list-of-positions-4-1-2-of-arbitrary-length-to-an-index-for-a-nested/6618179#6618179">this answer</a> also contains my stack-based solution. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload