使用多个范围语句的 Python 列表初始化

2022-01-24 00:00:00 python list initialization range

问题描述

我想要一个长列表,例如 [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.

相关文章