Python has no function for list index argument in __getitem()__, __setitem()__, __delitem()__. Since I have been an R user for long time, it looks quite natural to utilize list index. I know there is pandas or numpy but it is cumbersome to change the type. AND IT NEEDS IMPORTING EXTRA PACKAGE!
>>> import numpy as np
>>> lst = [1,2,3,4,5]
>>> np.array(lst)[[0,3,4]]
array([1, 4, 5])
Here is my proposal.
class list2(__builtins__.list):
def __getitem__(self, x):
if isinstance(x, __builtins__.list):
#print(x)
return [__builtins__.list.__getitem__(self, y) for y in x]
else:
return __builtins__.list.__getitem__(self,x)
def __setitem__(self, index, elem):
if isinstance(index, __builtins__.list):
if isinstance(elem, __builtins__.list):
for i,x in zip(index, elem):
__builtins__.list.__setitem__(self, i, x)
else:
for i in index:
__builtins__.list.__setitem__(self, i, elem)
#self[i] = x
else:
__builtins__.list.__setitem__(self, index, elem)
def __delitem__(self, index):
if isinstance(index, __builtins__.list):
for i in sorted(index, reverse = True):
__builtins__.list.__delitem__(self, i)
#self[i] = x
else:
__builtins__.list.__delitem__(self, index)
It seems to work okay.
>>> l = list2(['a', 'b', 'c', 'd', 'e'])
>>> l[[2,3]]
['c', 'd']
>>> l[[2,3]]= ['-', '-']
>>> l
['a', 'b', '-', '-', 'e']
>>> del l[[0,3]]
>>> l
['b', '-', 'e']
But is there any pitfall? or is there any part that needs to be improved?