Reputation: 78723
In Python, how can I create a list over a range with a fixed number of elements, rather than a fixed step between each element?
>>> # Creating a range with a fixed step between elements is easy:
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> # I'm looking for something like this:
>>> foo(0, 10, num_of_elements=4)
[0.0, 2.5, 5.0, 7.5]
Upvotes: 20
Views: 25061
Reputation: 28983
How about this:
>>> def foo(start=0, end=10, num_of_elements=4):
... if (end-start)/num_of_elements != float(end-start)/num_of_elements:
... end = float(end)
... while start < end:
... yield start
... start += end/num_of_elements
...
>>> list(foo(0, 10, 4))
[0, 2.5, 5.0, 7.5]
>>> list(foo(0, 10, 3))
[0, 3.3333333333333335, 6.666666666666667]
>>> list(foo(0, 20, 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
It keeps your specification for the first element to be an integer and the others to be floats. But if you give it a step where the elements can stay as integers, they will.
Upvotes: 0
Reputation: 1121644
You can easily produce such a list with a list comprehension:
def foo(start, stop, count):
step = (stop - start) / float(count)
return [start + i * step for i in xrange(count)]
This produces:
>>> foo(0, 10, 4)
[0.0, 2.5, 5.0, 7.5]
Upvotes: 9
Reputation: 19733
itertools.count
can handle float:
>>> import itertools
>>> def my_range(start,stop,count):
... step = (stop-start)/float(count)
... for x in itertools.count(start,step):
... if x < stop:
... yield x
... else:break
...
>>> [x for x in my_range(0,10,4)]
[0, 2.5, 5.0, 7.5]
Upvotes: 4
Reputation: 362617
I use numpy for this.
>>> import numpy as np
>>> np.linspace(start=0, stop=7.5, num=4)
array([ 0. , 2.5, 5. , 7.5])
>>> list(_)
[0.0, 2.5, 5.0, 7.5]
Upvotes: 39