0

I am quite new to Python (I'm more used to C, C#). I am trying to learn and I want to try to do things as 'Pythonic' as possible.

I want to iterate over intervals and then do something based on whether or not a number is in the interval. I know I can create my intervals using numpy.arrange (or some other array defintion) and then iterate over the bins like so

ibins = numpy.arange(start = 19, stop = 67, step = 2)
a = 50
for idx, val in enumerate(ibins) :
    if idx > 0:
        if ibins[idx - 1] <= a < ibins[idx] : 
            #do something more meaningfull
            print('Hello')

However, reading on various posts it is my understanding that using the index to access the bin elements is considered 'bad form' in Python.

What I would like to do is something more like this

for ibin in ibins
    if a is in ibin #somehow determine if a is in the bin
        print('Hello')

Is there a reasonable, short way to achieve this? Or is my first suggestion the best way to go.

I do not want to create custom interval-objects or things of that sort.

mortysporty
  • 2,749
  • 6
  • 28
  • 51

2 Answers2

1
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.

Anish Shah
  • 7,669
  • 8
  • 29
  • 40
1

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!
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111