简体   繁体   中英

How to create an array from a given array of ranges

I have this code:

    pg=[(10, 19), (30, 32), (37, 38), (50, 59), (63, 64),
    (69, 69), (120, 121), (124, 129), (130, 139), (160, 161),
    (164, 169), (180, 182), (185, 185), (189, 189), (190, 192),
    (194, 194), (196, 199), (260, 269), (270, 279), (300, 309),
    (330, 339), (358, 359), (360, 369)]

Those are given ranges, for example, pg[0] should be 10, pg[1] be 11, pg[2] be 12. and so on for the rest of the ranges. So I want the final array to be like this:

    pg=[10, 11, 12, 13 ....19, 30, 31,....,32,37, 38,50,51,....,59,63.. and so on]

How can I do this in python? Is it possible to do it without hard coding every range of elements in a new array?

Try this

l = []
for r in pg:
    l.extend(range(r[0], r[1]+1))

This is one approach using a list comprehension and itertools.chain (to flatten the list)

Ex:

from itertools import chain
pg=[(10, 19), (30, 32), (37, 38), (50, 59), (63, 64),
    (69, 69), (120, 121), (124, 129), (130, 139), (160, 161),
    (164, 169), (180, 182), (185, 185), (189, 189), (190, 192),
    (194, 194), (196, 199), (260, 269), (270, 279), (300, 309),
    (330, 339), (358, 359), (360, 369)]

result = list(chain.from_iterable([range(*i) for i in pg]))
print(result)

一个线性

 sum([list(range(x1, x2+1)) for x1, x2 in pg], [])

I guess the following might work

pg = [(10, 19), (30, 32), (37, 38), (50, 59), (63, 64),
    (69, 69), (120, 121), (124, 129), (130, 139), (160, 161),
    (164, 169), (180, 182), (185, 185), (189, 189), (190, 192),
    (194, 194), (196, 199), (260, 269), (270, 279), (300, 309),
    (330, 339), (358, 359), (360, 369)]
arr = []
for val in pg:
    arr += list(range(val[0], val[1] + 1))
print(arr)

One more example using list comprehension

a = [(10, 19), (30, 35)]
b = [j for i in a for j in range(i[0], i[1]+1)]
print(b) 

#output
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 30, 31, 32, 33, 34, 35]

with help of sum function also we can achieve this.

pg=[(10, 19), (30, 32), (37, 38), (50, 59), (63, 64),
    (69, 69), (120, 121), (124, 129), (130, 139), (160, 161),
    (164, 169), (180, 182), (185, 185), (189, 189), (190, 192),
    (194, 194), (196, 199), (260, 269), (270, 279), (300, 309),
    (330, 339), (358, 359), (360, 369)]      

print (list(sum(pg,())))

#output:[10, 19, 30, 32, 37, 38, 50, 59, 63, 64, 69, 69, 120, 121, 124, 129, 130, 139, 
#160, 161, 164, 169, 180, 182, 185, 185, 189, 189, 190, 192, 194, 194, 196, 199, 260, 
#269, 270, 279, 300, 309, 330, 339, 358, 359, 360, 369]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM