在python中生成任意长度的数字升序列表

发布于 2024-09-30 15:56:05 字数 93 浏览 0 评论 0原文

我可以调用一个返回升序数字列表的函数吗?即,function(10) 会返回[0,1,2,3,4,5,6,7,8,9]

Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萤火眠眠 2024-10-07 15:56:05

您想要 range()

def my_func(min, max)->list:     
    return list(range(min, max))

You want range().

def my_func(min, max)->list:     
    return list(range(min, max))
软糖 2024-10-07 15:56:05

range(10) 是内置的。

range(10) is built in.

凉墨 2024-10-07 15:56:05

如果您想要一个能够提供一系列不确定长度的迭代器,可以使用 itertools.count()。这里我使用 range() 进行迭代,因此循环有限制。

>>> import itertools
>>> for x, y in zip(range(10), itertools.count()):
...     print x, y
... 
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

稍后:另外,在 python 3.x 中,range() 返回一个迭代器,而不是一个列表。在这种情况下,您需要 list(range(10))

If you want an iterator that gives you a series of indeterminate length, there is itertools.count(). Here I am iterating with range() so there is a limit to the loop.

>>> import itertools
>>> for x, y in zip(range(10), itertools.count()):
...     print x, y
... 
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

Later: also, range() returns an iterator, not a list, in python 3.x. in that case, you want list(range(10)).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文