Python list initialization using multiple range statements

后端 未结 7 1612
误落风尘
误落风尘 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)))
    

提交回复
热议问题