Python list initialization using multiple range statements(使用多个范围语句的 Python 列表初始化)
问题描述
我想要一个长列表,例如 [1,2,3,4,5,15,16,17,18,19].为了初始化它,我尝试输入:
I want one long list, say [1,2,3,4,5,15,16,17,18,19] as an example. To initialize this, I try typing:
new_list = [range(1,6),range(15,20)]
但是这并没有做我想要的,返回:
However this doesn't do what I want, returning:
[[1, 2, 3, 4, 5], [15, 16, 17, 18, 19]]
当我这样做时:
len(new_list)
它返回 2,而不是我想要的 10 个元素(因为它在列表中创建了 2 个列表).显然,在这个例子中,我可以只输入我想要的内容,但我正在尝试对一些奇怪的迭代列表执行此操作,例如:
It returns 2, instead of the 10 elements I wanted (since it made 2 lists inside the list). Obviously in this example I could just type out what I want, but I'm trying to do this for some odd iterated lists that go like:
new_list = [range(101,6284),8001,8003,8010,range(10000,12322)]
需要一维列表而不是列表列表(或任何最好的名称).我猜这真的很容易而且我很想念它,但是经过相当多的搜索后,我没有想出任何有用的东西.有什么想法吗?
Desiring a 1-D list instead of a list of lists (or whatever it's best called). I'm guessing this is really easy and I'm missing it, but after quite a bit of searching I've come up with nothing too useful. Any ideas?
推荐答案
在 Python 2.x 上试试这个:
Try this for Python 2.x:
range(1,6) + range(15,20)
或者如果你使用的是 Python3.x,试试这个:
Or if you're using Python3.x, try this:
list(range(1,6)) + list(range(15,20))
用于处理中间元素,对于 Python 2.x:
For dealing with elements in-between, for Python 2.x:
range(101,6284) + [8001,8003,8010] + range(10000,12322)
最后是处理中间元素,对于 Python 3.x:
And finally for dealing with elements in-between, for Python 3.x:
list(range(101,6284)) + [8001,8003,8010] + list(range(10000,12322))
这里要记住的关键方面是,在 Python 2.x 中 range
返回一个列表,而在 Python 3.x 中它返回一个可迭代对象(因此需要将其显式转换为列表).对于将列表附加在一起,您可以使用 +
运算符.
The key aspects to remember here is that in Python 2.x range
returns a list and in Python 3.x it returns an iterable (so it needs to be explicitly converted to a list). And that for appending together lists, you can use the +
operator.
这篇关于使用多个范围语句的 Python 列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用多个范围语句的 Python 列表初始化


基础教程推荐
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01