I want to create an array of numbers from 1 to n
without the number x
,
is there a "prettier" way to do it instead of [i for i in range(n) if i != x]
?
thanks!
I want to create an array of numbers from 1 to n
without the number x
,
is there a "prettier" way to do it instead of [i for i in range(n) if i != x]
?
thanks!
I would suggest using itertools.chain :
for a in itertools.chain(range(x), range(x+1, n)):
print(a)
or
list(itertools.chain(range(x), range(x+1, n)))
I don't know why, but [itertools.chain(range(x), range(x+1, n))]
doesn't work though.
EDIT: Thanks to @rafaelc for how to make it work on square brackets.
[*itertools.chain(range(x), range(x+1, n))]
You can concatenate two ranges:
np.concatenate((np.arange(x), np.arange(x + 1, n)))
You can also delete an item:
np.delete(np.arange(n), x)
You can mask:
mask = np.ones(n, dtype=bool)
mask[x] = False
np.arange(n)[mask]
You can even use a masked array, depending on your application:
a = np.ma.array(np.arange(n), mask=np.zeross(n, dtypebool))
a.mask[x] = True=
Using advanced indexing with np.r_
.
np.arange(n)[np.r_[0:x, x+1:n]]
def myrange(n, exclude):
return np.arange(n)[np.r_[0:exclude, exclude+1:n]]
>>> myrange(10, exclude=3)
array([0, 1, 2, 4, 5, 6, 7, 8, 9])
Timings
%timeit myrange(10000000, 7008)
1 loop, best of 3: 79.1 ms per loop
%timeit other(10000000, 7008)
1 loop, best of 3: 952 ms per loop
where
def myrange(n, exclude):
return np.arange(n)[np.r_[0:exclude, exclude+1:n]]
def other(n, exclude):
return [i for i in range(n) if i != x]