gpt4 book ai didi

python - 按连续序列对整数列表进行分组

转载 作者:太空狗 更新时间:2023-10-29 17:58:12 32 4
gpt4 key购买 nike

我有一个整数列表...

[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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com