Python在列表中展开整数并对它们进行排序

时间:2014-04-16 20:07:10

标签: python

我有一个清单:

l = [[120,137],[112,119]]

我想扩展数字并对它们进行排序......预期输出:

newl = [112, 113,....,119,120,121...,137]

感谢您的任何建议......

3 个答案:

答案 0 :(得分:2)

>>> list_ = [[120,137],[112,119]]
>>> sorted(n for low, high in list_ for n in range(low, high + 1))
[112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137]

答案 1 :(得分:2)

这样做的一种方法是

>>> xx = []
>>> for x in l:
...   a, b = x[0], x[1]
...   xx += range(a, b+1)
... 
>>> xx
[120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 112, 113, 114, 115, 116, 117, 118, 119]
>>> sorted(xx)
[112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137]
>>> 

或者只是(根据@ wim的评论):

for a, b in l:
    xx += range(a, b+1)

应该够了

答案 2 :(得分:2)

>>> import itertools    
>>> l = [[120,137],[112,119]]
>>> sorted(itertools.chain.from_iterable([range(i[0],i[1]+1) for i in l]))
[112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137]