1

Suppose I have a tuple of (1, 2, 3) and want to index a multidimensional array with it such as:

index = (1, 2, 3)
table[index] = 42 # behaves like table[1][2][3]

index has an unknown number of dimensions, so I can't do:

table[index[0]][index[1]][index[2]]

I know I could do something like this:

functools.reduce(lambda x, y: x[y], index, table)

but it's utterly ugly (and maybe also inefficient), so I wonder if there's a better, more Pythonic choice.

EDIT: Maybe a simple loop is best choice:

elem = table
for i in index:
    elem = elem[i]

EDIT2: Actually, there's a problem with both solutions: I can't assign a value to the indexed array :-(, back to ugly:

elem = table
for i in index[:-1]:
    elem = elem[i]
elem[index[-1]] = 42

1 Answer 1

3

The question is very interesting and also your suggested solution looks good (havn't checked it, but this kind of problem requires a recursive treatment and you just did it in one line). However, the pythonic way I use in my programs is to use dictionaries of tuples. The syntax is array-like, the performance - of a dictionary, and there was no problem in it for me.

For example:

a = {(1, 2, 3): 'A', (3, 4, 5): 'B', (5, 6, 7, 8): 'C'}
print a[1, 2, 3]
print a[5, 6, 7, 8]

Will output:

A
B

And assigning to an index is super easy: a[1, 4, 5] = 42. (But you might want to first check that (1, 4, 5) is within the dict, or else it will be created by the assignment)

1
  • Clever solution! However, my array is actually a contiguous ctypes.c_float, can't use dictionaries there. Nice answer nonetheless. Mar 26, 2012 at 23:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.