'Python: making list of slices
How can I make this code better:
slices = [slice(0,10), slice(10,20), slice(20,30), slice(30,40), slice(40,50),
slice(50,60), slice(60, 70), slice(70, 80), slice(80,90), slice(90,100)]
for s in slices:
some_function(s)
Number is up to 800s and I do need to change slice range too.
Edit:
with concurrent.futures.ThreadpoolExecutor(max_workers=10) as exec:
slices = [slice(0,10), slice(10,20), slice(20,30),......]
for s in slices:
r = exec.map(some_function, some_list[s]))
Solution 1:[1]
You can try this:
start, end, slice_range = 0, 800, 10
for i in range(start, end, slice_range):
some_function(slice(i, i+slice_range))
The list can be completely eliminated, and you can also modify the range, start & stop point with just a single change! You can read more about range function here.
Solution 2:[2]
try to use List Comprehensions
start, end, step = 0, 100, 10
slices = [slice(i, i+step) for i in range(start, end, step)]
print(slices)
Solution 3:[3]
You can use the range() function, it returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
start, end, sliced_range = 0, 20, 10
for i in range(start, end, sliced_range):
your_function(slice(i, i+sliced_range))
Reference: w3schools.com/python/ref_func_range.asp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nowshad Ruhani Chowdhury |
| Solution 2 | maya |
| Solution 3 | Shah Zain |
