Created
May 6, 2019 09:16
-
-
Save stkrp/94f3c3443be92908450e228aab16b905 to your computer and use it in GitHub Desktop.
Multiple indexes
This file contains 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
class multiple_indexes(object): | |
""" Mixin """ | |
def __getitem__(self, index): | |
if not isinstance(index, tuple): | |
index = (index, ) | |
getter = super().__getitem__ | |
retval = [] | |
for i in index: | |
part = getter(i) | |
if isinstance(i, slice): | |
retval.extend(part) | |
else: | |
retval.append(part) | |
return retval | |
class my_list(multiple_indexes, list): | |
pass | |
class my_str(multiple_indexes, str): | |
def __getitem__(self, index): | |
return ''.join(super().__getitem__(index)) | |
if __name__ == '__main__': | |
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] | |
# [0, 1, 4, 6, 8, 15] | |
l = my_list(range(20)) | |
print(l, l[0:2, 4:10:2, 15]) | |
# 012345678910111213141516171819 | |
# 014682 | |
s = my_str(''.join(map(str, range(20)))) | |
print(s, s[0:2, 4:10:2, 15]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment