Python - 创建包含 2 个值之间的数字的列表? [英] Python - Create list with numbers between 2 values?
问题描述
如何创建一个列表,其中的值介于我输入的两个值之间?例如,为 11 到 16 的值生成以下列表:
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:
list = [11, 12, 13, 14, 15, 16]
推荐答案
使用 <代码>范围代码>.在 Python 2.x 中,它返回一个列表,因此您只需要:
Use range
. In Python 2.x it returns a list so all you need is:
>>> range(11, 17)
[11, 12, 13, 14, 15, 16]
在 Python 3.x 中 range
是一个迭代器.因此,您需要将其转换为列表:
In Python 3.x range
is a iterator. So, you need to convert it to a list:
>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]
注意:第二个数字是独占的.所以,这里需要 16+1
= 17
Note: The second number is exclusive. So, here it needs to be 16+1
= 17
要回答关于以 0.5
递增的问题,最简单的选择可能是使用 numpy 的 arange()
和 .tolist()代码>
:
To respond to the question about incrementing by 0.5
, the easiest option would probably be to use numpy's arange()
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]
这篇关于Python - 创建包含 2 个值之间的数字的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!