简体   繁体   English

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

[英]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.这些是给定的范围,例如, pg[0]应该是 10, pg[1]应该是 11, pg[2]是 12。对于其余的范围,依此类推。 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?我怎么能在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)这是使用列表itertools.chainitertools.chain (扁平化列表)的一种方法

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.在 sum 函数的帮助下,我们也可以实现这一点。

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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