Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

python - Python - 使用2个值之间的数字创建列表?(Python - Create list with numbers between 2 values?)

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]
  ask by lorde translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use range .

(使用range 。)

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

(在Python 2.x中它返回一个列表,所以你需要的只是:)

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

In Python 3.x range is a iterator.

(在Python中,3.x range是一个迭代器。)

So, you need to convert it to a list:

(因此,您需要将其转换为列表:)

>>> 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 's arange ,

(要回答关于递增0.5的问题,最简单的选择可能是使用numpyarange ,)

>>> numpy.arange(11, 17, 0.5)
array([ 11. ,  11.5,  12. ,  12.5,  13. ,  13.5,  14. ,  14.5,  15. ,
        15.5,  16. ,  16.5])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...