numpy - Is there a built-in method for checking individual list indices in Python -
python has built in functionality checking validity of entire slices: slice.indices
. there similar built-in individual indices?
specifically, have index, a = -2
wish normalize respect 4-element list. there method equivalent following built in?
def check_index(index, length): if index < 0: index += length if index < 0 or index >= length: raise indexerror(...)
my end result able construct tuple single non-none
element. using list.__getitem__
check me, seems little awkward/overkill:
items = [none] * 4 items[a] = 'item' items = tuple(items)
i able do
a = check_index(a, 4) items = tuple('item' if == else none in range(4))
everything in example pretty negotiable. things fixed getting a
in way can have of problems arbitrary index can have , final result has tuple
.
i more happy if solution used numpy , applied numpy arrays instead of python sequences. either 1 perfect application have in mind.
if understand correctly, can use range(length)[index]
, in example range(4)[-2]
. handles negative , out-of-bounds indices. @ least in recent versions of python, range()
doesn't literally create full list have decent performance large arguments.
if have large number of indices in parallel, might better performance doing calculation numpy vectorized arithmetic, don't think technique range
work in case. you'd have manually calculation using implementation in question.
Comments
Post a Comment