Python 3 将范围转换为列表 [英] Python 3 turn range to a list
问题描述
我正在尝试制作一个包含数字 1-1000
的列表.显然,写/读会很烦人,所以我试图制作一个包含范围的列表.在 Python 2 中,似乎:
I'm trying to make a list with numbers 1-1000
in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In Python 2 it seems that:
some_list = range(1,1000)
本来可行,但在 Python 3 中,范围类似于 Python 2 的 xrange
?
would have worked, but in Python 3 the range is similar to the xrange
of Python 2?
有人可以对此提供一些见解吗?
Can anyone provide some insight into this?
推荐答案
你可以只从范围对象构造一个列表:
You can just construct a list from the range object:
my_list = list(range(1, 1001))
这也是你在 python2.x 中使用生成器的方式.通常来说,您可能不需要列表,因为您可以更有效地使用 my_list[i]
的值(i + 1
),如果您只是需要迭代它,你可以回到 range
.
This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of my_list[i]
more efficiently (i + 1
), and if you just need to iterate over it, you can just fall back on range
.
还要注意,在 python2.x 上,xrange
仍然是可索引的1.这意味着python3.x上的range
也有相同的属性2
Also note that on python2.x, xrange
is still indexable1. This means that range
on python3.x also has the same property2
1print xrange(30)[12]
适用于 python2.x
1print xrange(30)[12]
works for python2.x
2python3.x 中与 1 类似的语句是 print(range(30)[12])
和也可以.
2The analogous statement to 1 in python3.x is print(range(30)[12])
and that works also.
这篇关于Python 3 将范围转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!