如何从给定范围的数组创建数组

时间:2019-01-31 11:20:57

标签: python arrays range

我有此代码:

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

已指定了这些范围,例如,pg[0]应该为10,pg[1]应该为11,pg[2]应该为12,以此类推。因此,我希望的最终排列是这样的:

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

如何在python中执行此操作?是否可以在不对新数组中的每个元素范围进行硬编码的情况下做到这一点?

6 个答案:

答案 0 :(得分:2)

尝试一下

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

答案 1 :(得分:2)

这是一种使用列表理解和itertools.chain(使列表变平)的方法

例如:

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)

答案 2 :(得分:2)

单线性

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

答案 3 :(得分:2)

我想以下方法可能有效

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)

答案 4 :(得分:1)

使用列表推导的另一个示例

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]

答案 5 :(得分:0)

借助求和函数,我们也可以实现这一目标。

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]