在python中制作一个在一定范围内的等距数字列表 [英] Making a list of evenly spaced numbers in a certain range in python
本文介绍了在python中制作一个在一定范围内的等距数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
制作任意长度的列表的Python方法是什么,该列表包含给定范围之间的均匀间隔的数字(而不仅仅是整数)?例如:
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 ]
请注意,Range()
函数仅处理整数.而这个:
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:
包括正确的端点(5):
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. ])
不包括正确的端点:
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])
这篇关于在python中制作一个在一定范围内的等距数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文