Identify groups of varying continuous numbers in a list

前端 未结 4 837
囚心锁ツ
囚心锁ツ 2020-12-17 20:56

In this other SO post, a Python user asked how to group continuous numbers such that any sequences could just be represented by its start/end and any stragglers would be dis

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 22:00

    I came across such a case once. Here it goes.

    import more_itertools as mit
    iterable = [2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20]  # input
    x = [list(group) for group in mit.consecutive_groups(iterable)]
    output = [(i[0],i[-1]) if len(i)>1 else i[0] for i in x]
    print(output)
    

提交回复
热议问题