__getitem__ With Slices On A List Of Lists
I'm creating a class representing a list of lists. __getitem__ is giving me headaches. Everything goes swimmingly until I introduce slices as parameters. Demonstration code # Pytho
Solution 1:
You probably want to change your syntax for mutidimensional access from obj[row][col]
to using a single tuple index: obj[row, col]
. This is the format numpy
's ndarray
type uses, and its very helpful, as it lets you see all the dimentions of the index at once. You can write a __getitem__
that will allow slicing in any dimension:
def__getitem__(self, index):
row, col = index
ifisinstance(row, int) andisinstance(col, (int, slice)):
return self._Cells[row][col]
elifisinstance(row, slice) andisinstance(col, (int, slice)):
return [r[col] for r in self._Cells[row]]
else:
raise TypeError, "Invalid argument type"
Solution 2:
The return from __getitem__
when index
is a slice is a list of lists:
[['.', '.', 'N', '.', '.'], ['.', 'C', 'A', 'T', '.'], ['.', '.', 'P', '.', '.']]
The second slice indexes into this list, rather than applying the slice to each item in the list.
To get the behaviour you're looking for, you could make NestedLists.__getitem__
return a new class, NestedListsSlice
when index
is a slice. This could then define its own __getitem__
to apply the second index to:
classNestedLists:
...
def__getitem__(self, index):
...
elifisinstance(index, slice):
return NestedListsSlice(self._Cells[index])
...
classNestedListsSlice():
def__init__(self, _Cells):
self._Cells = _Cells
def__getitem__(self, index):
ifisinstance(index, int) orisinstance(index, slice):
returnlist(x[index] for x in self._Cells)
else:
raise TypeError
Post a Comment for "__getitem__ With Slices On A List Of Lists"