2011-07-13 234 views
23

什么是在给定范围之间制作包含均匀间隔数字(而不仅仅是整数)的任意长度列表的pythonic方法?例如:在python中制作一定范围内的均匀间隔数字的列表

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 ] 

注意Range()函数只处理整数。而这个:

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 

好像太复杂了。有任何想法吗?

+0

有一些很好的解决方案:http://stackoverflow.com/questions/477486/python-decimal-range-step-value – Pill

+1

请注意,由于浮点数的(必要的)不准确性,这只适用于某些序列。 – delnan

回答

40

鉴于numpy的,你可以使用linspace

包括正确的端点(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.  ]) 

撇除右端点:

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

公平,这给你一个numpy阵列不列表... –

+5

@双AA:真;如果你需要一个列表,你可以使用'np.linspace(0,5,10).tolist()'。 – unutbu

23

您可以用下面的办法:

[lower + x*(upper-lower)/length for x in range(length)] 

下和/或上必须被指定为花车这种方法工作。

+3

如果numpy不可用,很高兴有一个简洁的股票python备选方案。 – feedMe

1
f = 0.5 
a = 0 
b = 9 
d = [x * f for x in range(a, b)] 

将是一种方式来做到这一点。

0

霍华德的答案,但更多的高效类似:

def my_func(low, up, leng): 
    step = ((up-low) * 1.0/leng) 
    return [low+i*step for i in xrange(leng)] 
4

与unutbu的答案类似,您可以使用numpy的arange函数,它类似于python的内部函数范围。请注意,不包括端点,如范围:

>>> import numpy as N 
>>> a=N.arange(0,5,0.5) 
>>> a 
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) 
>>> import numpy as N 
>>> a=N.arange(0,5,0.5) # returns a numpy array 
>>> a 
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) 
>>> a.tolist() # if you prefer it as a list 
[0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5] 
+0

或简单地说: a = N.arange(0,5,0.5).tolist() – nvd

+2

但是,使用numpy.arange()时要小心,但端点不能一致处理,会导致不可靠的行为,请参见[here]( http://quantumwise.com/forum/index.php?topic=110.0)。 – lhcgeneva

1

您可以使用如下因素代码:

def float_range(initVal, itemCount, step): 
    for x in xrange(itemCount): 
     yield initVal 
     initVal += step 

[x for x in float_range(1, 3, 0.1)]