Dou*_* AA 37 python list range
在给定边界之间制作包含均匀间隔数字(不仅仅是整数)的任意长度列表的pythonic方法是什么?例如:
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 ]
Run Code Online (Sandbox Code Playgroud)
请注意,该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
Run Code Online (Sandbox Code Playgroud)
看起来太复杂了.有任何想法吗?
unu*_*tbu 57
给定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. ])
Run Code Online (Sandbox Code Playgroud)
排除正确的终点:
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])
Run Code Online (Sandbox Code Playgroud)
How*_*ard 32
您可以使用以下方法:
[lower + x*(upper-lower)/length for x in range(length)]
Run Code Online (Sandbox Code Playgroud)
必须将lower和/或upper指定为浮点才能使用此方法.
与unutbu的答案类似,你可以使用numpy的arange函数,它类似于Python的内部函数range.请注意,不包括终点,如range:
>>> import numpy as np
>>> a = np.arange(0,5, 0.5)
>>> a
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])
>>> a = np.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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103616 次 |
| 最近记录: |