我有一个整数列表...

[1,2,3,4,5,8,9,10,11,200,201,202]

我想将它们分组到一个列表列表中,其中每个子列表都包含其序列未中断的整数。像这样...
[[1,5],[8,11],[200,202]]

我周围工作比较笨拙...
lSequenceOfNum = [1,2,3,4,5,8,9,10,11,200,201,202]

lGrouped = []
start = 0
for x in range(0,len(lSequenceOfNum)):
    if x != len(lSequenceOfNum)-1:
        if(lSequenceOfNum[x+1] - lSequenceOfNum[x]) > 1:
            lGrouped.append([lSequenceOfNum[start],lSequenceOfNum[x]])
            start = x+1

    else:
        lGrouped.append([lSequenceOfNum[start],lSequenceOfNum[x]])
print lGrouped

这是我所能做的最好的。有没有更“pythonic”的方式来做到这一点?谢谢..

最佳答案

假设列表将始终按升序排列:

from itertools import groupby, count

numberlist = [1,2,3,4,5,8,9,10,11,200,201,202]

def as_range(g):
    l = list(g)
    return l[0], l[-1]

print [as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c))]

关于python - 按连续序列对整数进行分组的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10420464/

10-09 08:08