Python list initialization using multiple range statements

后端 未结 7 1535
误落风尘
误落风尘 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:47

    You can use itertools.chain to flatten the output of your range() calls.

    import itertools
    new_list = list(itertools.chain(xrange(1,6), xrange(15,20)))
    

    Using xrange (or simply range() for python3) to get an iterable and chaining them together means only one list object gets created (no intermediate lists required).

    If you need to insert intermediate values, just include a list/tuple in the chain:

    new_list = list(itertools.chain((-3,-1), 
                                    xrange(1,6), 
                                    tuple(7),  # make single element iterable
                                    xrange(15,20)))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 22:57

    Try this:

    from itertools import chain
    
    new_list = [x for x in chain(range(1,6), range(15,20))]
    print new_list
    

    Output like you wanted:

    [1, 2, 3, 4, 5, 15, 16, 17, 18, 19]
    
    0 讨论(0)
  • 2021-01-07 23:01

    Just unpack the range values as follows:

    new_list = [*range(1,6), *range(15,20)]
    
    print(new_list)
    # [1, 2, 3, 4, 5, 15, 16, 17, 18, 19]
    
    print(len(new_list))
    # 10
    
    print(type(new_list))
    # <class 'list'>
    
    0 讨论(0)
  • 2021-01-07 23:01

    i would like to propose u a version without +

    import operator
    a = list(range(1,6))
    b = list(range(7,9))
    print(operator.concat(a,b))
    
    0 讨论(0)
  • 2021-01-07 23:05

    range returns a list to begin with, so you need to either concatenate them together with + or use append() or extend().

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

    or

    new_list = range(101,6284)
    mew_list.extend([8001,8003,8010])
    mew_list.extend(range(10000,12322))
    

    Alternatively, you could use itertools.chain() as shown in Shawn Chin's answer.

    0 讨论(0)
提交回复
热议问题