Lon*_*Rob 10 python floating-point range python-2.7
在Python 2.7中,如何在具有固定数量元素的范围上创建列表,而不是在每个元素之间固定步长?
>>> # 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]
Run Code Online (Sandbox Code Playgroud)
wim*_*wim 16
我为此使用了numpy.
>>> 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]
Run Code Online (Sandbox Code Playgroud)
您可以使用列表理解轻松生成这样的列表:
def foo(start, stop, count):
step = (stop - start) / float(count)
return [start + i * step for i in xrange(count)]
Run Code Online (Sandbox Code Playgroud)
这会产生:
>>> foo(0, 10, 4)
[0.0, 2.5, 5.0, 7.5]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6276 次 |
| 最近记录: |