综合编程

Make a list of evenly spaced numbers in a certain range of python

微信扫一扫,分享到朋友圈

Make a list of evenly spaced numbers in a certain range of python
0

What is a pythonic way of making list of arbitrary length containing evenly spaced numbers (not just whole integers) between given bounds? For instance:

my_func(0,5,10) # ( lower_bound , upper_bound , length )
# [ 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5 ]

Note the Range()
function only deals with integers. And this:

def my_func(low,up,leng):
    list = []
    step = (up - low) / float(leng)
    for i in range(leng):
        list.append(low)
        low = low + step
    return list

seems too complicated. Any ideas?

Given numpy, you could use linspace
:

Including the right endpoint (5):

In [46]: import numpy as np
In [47]: np.linspace(0,5,10)
Out[47]:
array([ 0.        ,  0.55555556,  1.11111111,  1.66666667,  2.22222222,
        2.77777778,  3.33333333,  3.88888889,  4.44444444,  5.        ])

Excluding the right endpoint:

In [48]: np.linspace(0,5,10,endpoint=False)
Out[48]: array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5,  4. ,  4.5])

阅读原文...


Hello, buddy!

US iPhone users spent $79 last year, up 36% from 2017

上一篇

Managed Images on Azure Stack

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Make a list of evenly spaced numbers in a certain range of python

长按储存图像,分享给朋友