Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to index nested lists using tuples in python?

I just started with python and very soon wondered if indexing a nested list with a tuple was possible. Something like: elements[(1,1)]

One example where I wanted to do that was something similar to the code below in which I save some positions of the matrix that I will later need to access in a tuple called index.

index = ( (0,0), (0,2), (2,0), (2,2) )

elements = [ [ 'a', 'b', 'c'],
             [ 'c', 'd', 'e'],
             [ 'f', 'g', 'h'] ]

for i in index:
    print (elements [ i[0] ] [ i[1] ])

    # I would like to do this:
    # print(elements[i])

It seems like a useful feature. Is there any way of doing it? Or perhaps a simple alternative?

like image 909
Aodh Ross Avatar asked May 20 '15 05:05

Aodh Ross


2 Answers

If you really want to use tuples for indexing you can implement your own class that extends list and redefines __getattr__ to work with tuples and use that:

class TList(list):
    def __getitem__(self, index):
        if hasattr(index, "__iter__"):
            # index is list-like, traverse downwards
            item = self
            for i in index:
                item = item[i]
            return item
        # index is not list-like, let list.__getitem__ handle it
        return super().__getitem__(index)

elements = TList([ [ 'a', 'b', 'c'],
                   [ 'c', 'd', 'e'],
                   [ 'f', 'g', 'h'] ])
index = ( (0,0), (0,2), (2,0), (2,2) )
for i in index:
    print(elements[i])

a
c
f
h

like image 140
Raniz Avatar answered Sep 28 '22 05:09

Raniz


Yes, you can do that. I wrote a similar example:

index = [ [0,0], [0,2], [2,0], [2,2] ]

elements = [ [ 'a', 'b', 'c'],
             [ 'c', 'd', 'e'],
             [ 'f', 'g', 'h'] ]

for i,j in index:
    print (elements [ i ] [ j ])

a c f h

like image 21
Ryan Avatar answered Sep 28 '22 07:09

Ryan