Create a range with a fixed number of elements (length)

In Python 2.7, how can I create a list by 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: >>> 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, 7.5] 
+6
source share
4 answers

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] 
+8
source

You can easily create a combo box like this:

 def foo(start, stop, count): step = (stop - start) / float(count) return [start + i * step for i in xrange(count)] 

This gives:

 >>> foo(0, 10, 4) [0.0, 2.5, 5.0, 7.5] 
+6
source

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] 
+2
source

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 saves your specification so that the first element is integer and the rest are floating. But if you give him a step where the elements can remain intact, they will be.

0
source

Source: https://habr.com/ru/post/978469/


All Articles