I'm curious about the fastest way to get a list without * changes * to the list ʻitems * without ʻitems [i]
, or a reasonably fast and smart way to write (sometimes excluding the i-th in math). , Because I want something like that).
I measured it with % timeit
of Jupyter.
items = list(range(1000000))
i = 17 #suitable
%timeit items[:i] + items[i+1:]
11.2 ms ± 349 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit [item for k, item in enumerate(items) if k != i]
65.1 ms ± 212 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit [items[k] for k in range(len(items)) if k != i]
75.5 ms ± 800 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
It seems that slicing is overwhelmingly faster. By the way, I was a little surprised that using the second ʻenumerate` is faster than the third example.
@ antimon2's Maru Park, but there are the following methods.
import numpy as np
items = np.arange(1000000)
i = 17
np.hstack
%timeit np.hstack([items[:i], items[i+1:]])
584 µs ± 6.32 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
np.delete
%timeit np.delete(items, i)
585 µs ± 3.73 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit items[np.arange(items.size) != i]
1.9 ms ± 5.82 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit np.array([items[k] for k in range(len(items)) if k != i])
182 ms ± 3.85 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Again, the slices combine very quickly. Considering readability, is np.delete
the best because the speed does not change so much?
If you have any other good ones, please let me know.
Recommended Posts