Python - 创建包含 2 个值之间的数字的列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18265935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:20:03  来源:igfitidea点击:

Python - Create list with numbers between 2 values?

pythonlist

提问by lorde

How would I create a list with values between two values I put in? For example, the following list is generated for values from 11 to 16:

我将如何创建一个列表,其中的值介于我输入的两个值之间?例如,为 11 到 16 的值生成以下列表:

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

采纳答案by Jared

Use range. In Python 2.x it returns a list so all you need is:

使用range. 在 Python 2.x 中,它返回一个列表,因此您只需要:

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

In Python 3.x rangeis a iterator. So, you need to convert it to a list:

在 Python 3.x 中range是一个迭代器。因此,您需要将其转换为列表:

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

Note: The second number is exclusive. So, here it needs to be 16+1= 17

注意:第二个数字是独占的。所以,这里需要16+1=17

EDIT:

编辑:

To respond to the question about incrementing by 0.5, the easiest option would probably be to use numpy'sarange()and .tolist():

要回答关于 incrementing by 的问题0.5,最简单的选择可能是使用numpy'sarange()and .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]

回答by devnull

You seem to be looking for range():

您似乎在寻找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]

For incrementing by 0.5instead of 1, say:

对于递增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]

回答by Bhargav Ponnapalli

Use list comprehension in python. Since you want 16 in the list too.. Use x2+1. Range function excludes the higher limit in the function.

在 python 中使用列表理解。由于您也想要列表中的 16.. 使用 x2+1。范围函数不包括函数中的上限。

list=[x for x in range(x1,x2+1)]

list=[x for x in range(x1,x2+1)]

回答by v2b

assuming you want to have a range between x to y

假设您想要 x 到 y 之间的范围

range(x,y+1)

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

use list for 3.x support

使用 3.x 支持列表

回答by Mike Housky

Try:

尝试:

range(x1,x2+1)  

That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:

这是 Python 2.x 中的列表,其行为与 Python 3.x 中的列表非常相似。如果您正在运行 Python 3 并且需要一个可以修改的列表,请使用:

list(range(x1,x2+1))

回答by Rajesh Surana

If you are looking for range like function which works for float type, then here is a very good article.

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

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))    

Output:

输出:

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]

回答by Denis Rasulev

Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

上面的每个答案都假设范围仅为正数。这是返回连续数字列表的解决方案,其中参数可以是任何(正或负),并且可以设置可选的步长值(默认值 = 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

For instance, standard command list(range(1,-3))returns empty list [], while this function will return [-3,-2,-1,0,1]

例如,标准命令list(range(1,-3))返回空列表[],而此函数将返回[-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.

更新:现在步骤可能为负。感谢@Michael 的评论。

回答by Michael

The most elegant way to do this is by using the rangefunction however if you want to re-create this logic you can do something like this :

最优雅的方法是使用该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)]

This produces the output:

这会产生输出:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the rangeor numpy.arrangehowever I find the code interesting to be shared.

正如@Jared 之前所表达的那样,最好的方法是使用rangenumpy.arrange但是我发现共享代码很有趣。

回答by ashutosh pandey

In python you can do this very eaisly

在python中你可以很容易地做到这一点

start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]

or you can create a recursive function that returns an array upto a given number:

或者您可以创建一个递归函数,该函数返回一个数组,最多给定数字:

ar=[]
def diff(start,end):
    if start==end:
        d.append(end)
        return ar
    else:
        ar.append(end)
        return diff(start-1,end) 

output: ar=[10,9,8,7,6,5,4,3,2,1,0]

输出:ar=[10,9,8,7,6,5,4,3,2,1,0]