retrieve item from nested list given index tuple
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Aug 14 13:09:42 EDT 2009
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
> I don't want to use NumPy, but I'd like somehow to avoid an explicit
> loop. I did consider using eval. E.g., eval('lst' +
> '[%d]'*len(tpl)%tpl). It works but seems rather ugly.
And slow.
> I kind of like
> reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains
> controversial enough to see i removed from the Python 3 built-ins ...
It's just moved into functools.
>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']]
>>> from functools import reduce
>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']]
>>> reduce(list.__getitem__, (2, 1, 0), lst)
'aaa'
However, it doesn't work too well as soon as you mix sequence types:
>>> reduce(list.__getitem__, (2, 1, 0, 0), lst)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor '__getitem__' requires a 'list' object but received
a 'str'
Try this instead:
>>> from operator import getitem
>>> reduce(getitem, (2, 1, 0), lst)
'aaa'
>>> reduce(getitem, (2, 1, 0, 0), lst)
'a'
operator.getitem is less ugly too.
--
Steven
More information about the Python-list
mailing list