Created
August 24, 2019 00:45
-
-
Save davidmashburn/bb34c0d53bba1c58b90044165414b486 to your computer and use it in GitHub Desktop.
Fancy Indexing (simplified version)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _make_fancy(*args, **kwds): | |
return (fancyIndexingDict(*args, **kwds) | |
if len(kwds) or (len(args) and hasattr(args[0], 'keys')) else | |
fancyIndexingList(*args, **kwds)) | |
def _fancy_getitem(fancy_x, index): | |
index = index if hasattr(index, '__iter__') else (index, ) | |
index = index if type(index) is tuple else tuple(index) | |
if isinstance(fancy_x, fancyIndexingDict): | |
x = fancy_x._simple_getitem(index[0]) | |
return (x if len(index) <= 1 else | |
fancy_x._make_fancy(x)[index[1:]]) | |
else: | |
if len(index) == 1: | |
return ([fancy_x[i] for i in index[0]] | |
if hasattr(index[0], '__iter__') else | |
fancy_x._simple_getitem(index[0])) | |
elif type(index[0]) == slice: | |
return [fancy_x._make_fancy(f_i)[index[1:]] | |
for f_i in fancy_x[index[0]]] | |
elif hasattr(index[0], '__iter__'): | |
return [fancy_x._make_fancy(fancy_x[i])[index[1:]] | |
for i in index[0]] | |
else: | |
return fancy_x._make_fancy(fancy_x[index[0]])[index[1:]] | |
class fancyIndexingDict(dict): | |
def _make_fancy(self, *args, **kwds): | |
return _make_fancy(*args, **kwds) | |
def _simple_getitem(self, key): | |
return dict.__getitem__(self, key) | |
def __getitem__(self, index): | |
return _fancy_getitem(self, index) | |
class fancyIndexingList(list): | |
def _make_fancy(self, *args, **kwds): | |
return _make_fancy(*args, **kwds) | |
def _simple_getitem(self, index): | |
return list.__getitem__(self, index) | |
def __getitem__(self, index): | |
return _fancy_getitem(self, index) | |
def __getslice__(self, i, j): | |
return self.__getitem__(slice(i, j)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment