如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
当前回答
在python中使用列表理解式。既然你也想要16个。使用x2 + 1。Range函数不包括函数中的上限。
list=[x for x in range(x1, x2+1)]
其他回答
虽然@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():
>>> x1=11
>>> x2=16
>>> range(x1, x2+1)
[11, 12, 13, 14, 15, 16]
>>> list1 = range(x1, x2+1)
>>> list1
[11, 12, 13, 14, 15, 16]
如果要增加0.5而不是1,那么:
>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)]
>>> list2
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
在python中使用列表理解式。既然你也想要16个。使用x2 + 1。Range函数不包括函数中的上限。
list=[x for x in range(x1, x2+1)]
上面的每个答案都假设range仅为正数。下面是返回连续数字列表的解决方案,其中参数可以是任何(正或负),并可以设置可选的步长值(默认= 1)。
def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
return a
else:
mx = max(a,b)
mn = min(a,b)
result = []
# inclusive upper limit. If not needed, delete '+1' in the line below
while(mn < mx + 1):
# if step is positive we go from min to max
if s > 0:
result.append(mn)
mn += s
# if step is negative we go from max to min
if s < 0:
result.append(mx)
mx += s
return result
例如,标准命令列表(range(1,-3))返回空列表[],而此函数将返回[-3,-2,-1,0,1]
更新:现在的步骤可能是负的。谢谢@Michael的评论。
@YTZ的回答很适合我。我必须生成一个从0到10000的列表,步长为0.01,由于舍入问题,在每次迭代中简单地添加0.01是行不通的。
因此,我采纳了@YTZ的建议,编写了如下函数:
import numpy as np
def generate_floating_numbers_in_range(start: int, end: int, step: float):
"""
Generate a list of floating numbers within a specified range.
:param start: range start
:param end: range end
:param step: range step
:return:
"""
numbers = np.linspace(start, end,(end-start)*int(1/step)+1).tolist()
return [round(num, 2) for num in numbers]