本文介绍了产生一个“有效的"从数字列表编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我前几天正在考虑这个问题.假设您有数字列表:

I was thinking about this the other day. Say you have the list of numbers:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001

是否有任何库或代码可以将以下内容转换为类似:

is there any library or code snipped that will turn the following into something like:

1-13, 19, 21-23, 999-1001

换句话说,将完整的数字列表减少到一堆范围左右.我一直无法找到任何东西.如果不存在这样的东西,有人对有效实施有一些想法吗?

In other words, reduce a full list of numbers to a bunch of ranges or so. I haven't been able to find anything. If no such thing exists, anyone have some ideas for an efficient implementation?

推荐答案

def get_groups(lst):
    slices = [i+1 for i, v in enumerate(zip(lst, l[1:])) if v[0] != v[1]-1] 
    slices = [0] + slices + [len(lst)]
    for start, end in zip(slices, slices[1:]):
        yield lst[start:end]

>>> list(get_groups([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001]))
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [19], [21, 22, 23], [999, 1000, 1001]]

def get_ranges(lst):
    slices = [i+1 for i, v in enumerate(zip(lst, l[1:])) if v[0] != v[1]-1]
    slices = [0] + slices + [len(lst)]
    for start, end in zip(slices, slices[1:]):
        yield "%d-%d" % (lst[start], lst[end-1])

>>> list(get_ranges([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001]))
['1-13', '19-19', '21-23', '999-1001']

这篇关于产生一个“有效的"从数字列表编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:47