retrieve item from nested list given index tuple
davea at ieee.org
Fri Aug 14 21:32:40 CEST 2009
Colin J. Williams wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Steven
> D'Aprano wrote:
>> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote:
>>> `lst` is a nested list
>>> `tpl` is the indexes for an item in the list
>>> What is the nice way to retrieve the item? (Speedy access is nice.)
>> Assuming you want to do this frequently, write a helper function,
>> then use it:
>> # Untested
>> def extract(nested, indexes):
>> for index in indexes:
>> nested = nested[index]
>> return nested
> This looks OK for the first level of nesting. We are not told much
> about tpl but suppose that:
> lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f
> from lst. tpl would need to be something like [[1, 1, 1], [2, 1]].
> If that is the requirement, then Untested is only a step along the
> road, extract could be made recursive.
> Colin W.
You missed the point: he's retrieving *an* item from a list that's
nested arbitrarily. Each item in the tpl (tuple) is a simple integer.
More information about the Python-list