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

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

When I do:

len(new_list)

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?

解决方案

Try this for Python 2.x:

range(1,6) + range(15,20)

Or if you're using Python3.x, try this:

list(range(1,6)) + list(range(15,20))

For dealing with elements in-between, for Python 2.x:

range(101,6284) + [8001,8003,8010] + range(10000,12322)

And finally for dealing with elements in-between, for Python 3.x:

list(range(101,6284)) + [8001,8003,8010] + list(range(10000,12322))

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值