使用多个范围语句的Python列表初始化 [英] Python list initialization using multiple range statements
问题描述
我想要一个长列表,例如[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列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!