如何在两个值之间创建一个升序列表?例如,11和16之间的列表:

[11, 12, 13, 14, 15, 16]

当前回答

假设你想要一个x到y的范围

range(x,y+1)

>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>

3使用list。x的支持

其他回答

@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]

Try:

range(x1, x2+1)  

这是Python 2中的一个列表。在Python 3.x中,它的行为很像一个列表。如果你正在运行Python 3并且需要一个可以修改的列表,那么使用:

list(range(x1, x2+1))

如果你正在寻找适用于浮点类型的范围函数,那么这是一篇非常好的文章。

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]

上面的每个答案都假设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的评论。

在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]