如何生成连续数字列表? [英] How can I generate a list of consecutive numbers?
问题描述
说,如果您在python中输入了数字8
,并且想生成一个连续的数字列表,最高可达8
,例如
Say if you had a number input 8
in python and you wanted to generate a list of consecutive numbers up to 8
like
[0, 1, 2, 3, 4, 5, 6, 7, 8]
你怎么能做到这一点?
推荐答案
In Python 3, you can use the builtin range
function like this
>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
注1::Python 3.x的range
函数返回range
对象.如果需要列表,则需要使用 list
功能就像我在答案中所示.
Note 1: Python 3.x's range
function, returns a range
object. If you want a list you need to explicitly convert that to a list, with the list
function like I have shown in the answer.
注2:我们将数字9传递给range
函数,因为range
函数将生成直到给定数字的数字,但不包括该数字.因此,我们给实际数字+ 1.
Note 2: We pass number 9 to range
function because, range
function will generate numbers till the given number but not including the number. So, we give the actual number + 1.
注释3:在Python 2和3中,range
的功能略有不同.您可以在
Note 3: There is a small difference in functionality of range
in Python 2 and 3. You can read more about that in this answer.
这篇关于如何生成连续数字列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!