如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
当前回答
如果你正在寻找适用于浮点类型的范围函数,那么这是一篇非常好的文章。
def frange(start, stop, step=1.0):
''' "range()" like function which accept float type'''
i = start
while i < stop:
yield i
i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time.
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
print i # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))
输出:
1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]
其他回答
假设你想要一个x到y的范围
range(x,y+1)
>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>
3使用list。x的支持
在python中使用列表理解式。既然你也想要16个。使用x2 + 1。Range函数不包括函数中的上限。
list=[x for x in range(x1, x2+1)]
使用范围。在Python 2中,它直接返回一个列表:
>>> range(11, 17)
[11, 12, 13, 14, 15, 16]
在Python 3中,range是一个迭代器。将其转换为列表:
>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]
注意:范围内的第二个数字(start, stop)是排他的。所以,stop = 16+1 = 17。
要增加0.5,可以考虑使用numpy的arange()和.tolist():
>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
14.0, 14.5, 15.0, 15.5, 16.0, 16.5]
参见:如何为range()使用十进制步进值?
虽然@Jared关于增加0.5步长的答案有效,但由于舍入问题,它无法用于其他步长:
np.arange(11, 17, 0.1).tolist()
# [11.0,11.1,11.2,11.299999999999999, ... 16.79999999999998, 16.899999999999977]
相反,我自己也需要这样的工作,不只是挣0.5美元:
# Example 11->16 step 0.5
s = 11
e = 16
step = 0.5
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
# Example 0->1 step 0.1
s = 0
e = 1
step = 0.1
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
最优雅的方法是使用range函数,但是如果你想重新创建这个逻辑,你可以这样做:
def custom_range(*args):
s = slice(*args)
start, stop, step = s.start, s.stop, s.step
if 0 == step:
raise ValueError("range() arg 3 must not be zero")
i = start
while i < stop if step > 0 else i > stop:
yield i
i += step
>>> [x for x in custom_range(10, 3, -1)]
这将产生输出:
[10, 9, 8, 7, 6, 5, 4]
正如之前@Jared所表达的,最好的方法是使用range或numpy。然而,我发现代码很有趣,可以分享。