Python 3将范围转换为列表 [英] Python 3 turn range to a list

查看:289
本文介绍了Python 3将范围转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个数字1-1000的列表。显然,这将是恼人的写/读,所以我试图做一个范围在它的列表。在python 2似乎
some_list = range(1,1000)
将工作,但在python 3范围类似于python 2的xrange?

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) 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

sup> 1

2 在python3.x中 1 的类似语句是 print(range(30)[12] / code>,并且也工作。

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.

这篇关于Python 3将范围转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆