How can you loop across multiple different ranges. for example say i want to run a for loop for specific set of ranges
1 to 2, 4 to 6 and 10 to 13,
I don't know the exact final number so maybe a function might be useful.
The standard method of
for i in range(1,2) + range (4,6) + range (10,13)
I should have this
[1,4,5,6,10,11,13]
My question is, this is not so efficient, if i don't know the total number of ranges am covering, and I can't even create this as a function without so many parameters.
so if i want to have something like this
for i in range(a,b) + range (c,d) + range (e,f), .....
but as a simple function Can someone help with an efficient way of doing this ?
Simple, though most likely the least efficient solution is to use a nested for loop,
def multi_range_loop(ranges):
all_values = []
for rg in ranges:
for i in range(rg[0], rg[1]):
all_values.append(i)
print(all_values)
my_ranges = [[1,3],[4,7],[10,14]]
multi_range_loop(my_ranges)
You can chain the ranges with itertools:
from itertools import chain
total_range = chain(range(1,2), range(4,6), range(10,13))
print(list(total_range))
#[1, 4, 5, 10, 11, 12]
Here is another solution with a function that returns a generator:
def total_range(lst):
return (i for tup in lst for i in range(tup[0], tup[1]))
list_of_ranges = [(1,2), (4,6), (10,13)]
print(list(total_range(list_of_ranges)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With