Access multidimensional list value by tuple of indices in python -
i have complex multidimensional utterable object (say, list). want write function access value of element represented tuple of indices. number of dimensions variable. should return none
if element not exist:
l = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]] access(l, (0, 0, 0)) # prints 1 access(l, (0, 1, 1)) # prints 4 access(l, (1, 1)) # prints [7, 8] access(l, (0, 1, 2)) # prints none access(l, (0, 0, 0, 0)) # prints none
how achieve this?
you can using reduce()
:
def access(obj, indexes): return reduce(lambda subobj, index: subobj[index] if isinstance(subobj, list) , index < len(subobj) else none, indexes, obj)
or pointed @chepner, can use def
make more readable:
def access(obj, indexes): def _get_item(subobj, index): if isinstance(subobj, list) , index < len(subobj): return subobj[index] return none return reduce(_get_item, indexes, obj)
Comments
Post a Comment