Python list initialization using multiple range statements

后端 未结 7 1584
误落风尘
误落风尘 2021-01-07 22:15

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

7条回答
  •  自闭症患者
    2021-01-07 22:51

    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.

提交回复
热议问题