This is impossible to do with Python's range. But this can be accomplished by creating your own generator function.
def myRange(start,end,step):
i = start
while i < end:
yield i
i += step
yield end
for i in myRange(0,99,20):
print(i)
Output:
0
20
40
60
80
99
Answer from Neil on Stack OverflowVideos
This is impossible to do with Python's range. But this can be accomplished by creating your own generator function.
def myRange(start,end,step):
i = start
while i < end:
yield i
i += step
yield end
for i in myRange(0,99,20):
print(i)
Output:
0
20
40
60
80
99
First of all, it usually does not makes much sense to include the end condition, the idea of a range is to perform hops until the end value is reached.
Nevertheless, you can for instance use itertools.chain for that:
from itertools import chain
for i in chain(range(0,99,20), [99]):
# ...
pass
chain concatenates iterables together. So after the range(..) is exhausted, it will iterate over the next iterable, and so on.
The above approach is not very elegant: it requires some knowledge about how chain works. We can however encapsulate that logic:
def range_with_end(start, stop, step):
return chain(range(start, stop, step), (stop,)) start = 19
stop = 67
step = 2
for bin in [range(i, i+step) for i in range(start, stop, step)]:
if a in bin:
print('Hello')
If you're using Python 2, then xrange method is better than range.
there is a discussion of this here: Iteration over list slices
this is one of the shortest versions:
import numpy as np
lst = np.arange(start = 19, stop = 67, step = 2)
bin_width = 5
search = 50
for ibin in zip(*(iter(lst),) * bin_width):
print(ibin)
if min(ibin) <= search <= max(ibin):
print('found!')
# or this? not sure what you want...
if ibin[0] <= search <= ibin[-1]:
print('found!')
this prints
(19, 21, 23, 25, 27)
(29, 31, 33, 35, 37)
(39, 41, 43, 45, 47)
(49, 51, 53, 55, 57)
found!
found!
Ideally one would use threading to accomplish this. You can do something like
import threading
interval = 15
def myPeriodicFunction():
print "This loops on a timer every %d seconds" % interval
def startTimer():
threading.Timer(interval, startTimer).start()
myPeriodicFunction()
then you can just call
startTimer()
in order to start the looping timer.
Consider tracking the time it takes the code to run (a timer() function), then sleeping for 15 - exec_time seconds after completion.
start = datetime.now()
do_many_important_things()
end = datetime.now()
exec_time = end - start
time.sleep(15-exec_time.total_seconds())