-1

Let's say hypothetically you had a variable called list_a. Sometimes the objects inside are themselves also lists, so multiple indexing might be needed depending on what you want.

You have the following dictionary:

field_dict = {
    'name':[1],
    'birthdate':[2,5],
    'gender':[5,1,3]
}

Each value in the lists above represent how to index list_a to access the needed value.

To get a person's name, I just need to index list_a once, like this: list_a[1].

To access their birthdate, I do list_a[2][5]. This is where the multiple indexing comes in. Likewise, to access gender, I do list_a[5][1][3].

I wonder what the most elegant implementation of this would be - the only solutions I can think of would involve a bit of bruteforcing in the way of hard-coding some details excessively.

Yeahprettymuch
  • 501
  • 5
  • 16
  • Consider using a list of objects with each object being details about a person. – dawg Dec 24 '20 at 17:03
  • 1
    Hypothetically I wouldn’t use a list of lists, I’d use a list of Person objects – Sayse Dec 24 '20 at 17:03
  • 2
    I’m really curious what kind of data model leads to a three dimensional list of genders. That seems a little strange...sometimes the difficulty in coding a solution is a direct consequence of a bad data model. Maybe a refactor is worth thinking about? – Mark Dec 24 '20 at 17:07
  • That's just an example I cooked up to try and convey the matter, the question seemed interesting to ponder anyway because it never occurred me if indexing instructions could be saved as Python variables, as I've never done it before. – Yeahprettymuch Dec 24 '20 at 17:11
  • The duplicate I linked to asks about dictionaries, but it works pretty much the same with lists. – Barmar Dec 24 '20 at 17:18
  • @Yeahprettymuch, it might be worth your time to look at numpy. You can index into multi-dimensional numpy arrays with tuples of indices, which would simplify the indexing aspect of this. – Mark Dec 24 '20 at 17:19

1 Answers1

1

As noted in the comments, this does not seem like a great data model. But leaving that aside, I might implement the accessor like:

def get_item(obj, indices):
    if indices:
        return get_item(obj[indices[0]], indices[1:])
    else:
        return obj

or iteratively:

def get_item(obj, indices):
    while indices:
        obj = indices[0]
        indices = indices[1:]
    return obj
Samwise
  • 68,105
  • 3
  • 30
  • 44