如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
如何在两个值之间创建一个升序列表?例如,11和16之间的列表:
[11, 12, 13, 14, 15, 16]
当前回答
Try:
range(x1, x2+1)
这是Python 2中的一个列表。在Python 3.x中,它的行为很像一个列表。如果你正在运行Python 3并且需要一个可以修改的列表,那么使用:
list(range(x1, x2+1))
其他回答
在python中,你可以很容易地做到这一点
start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]
或者你可以创建一个递归函数,返回一个数组到给定的数字:
ar=[]
def diff(start,end):
if start==end:
d.append(end)
return ar
else:
ar.append(end)
return diff(start-1,end)
输出: 基于“增大化现实”技术=[10、9、8、7、6、5、4、3、2、1、0]
我来到这里是因为我想使用列表推导式创建一个增量为0.1的-10到10之间的范围。而不是像上面大多数答案那样做一个过于复杂的函数,我只是这样做了
simple_range = [ x*0.1 for x in range(-100, 100) ]
通过将范围计数更改为100,我现在通过使用标准范围函数得到了从-10到10的范围。所以如果你需要0.2,那么就做范围(- 200,200)等等
最优雅的方法是使用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。然而,我发现代码很有趣,可以分享。
上面的每个答案都假设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的评论。
你似乎在寻找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]