Giovanni Funchal
Giovanni Funchal

Reputation: 9190

Indexing an array with a tuple

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

Upvotes: 1

Views: 288

Answers (1)

Israel Unterman
Israel Unterman

Reputation: 13510

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)

Upvotes: 3

Related Questions