将数字列表(重复的数字)合并到范围内

时间:2019-09-26 06:58:53

标签: python python-3.x itertools

我想将数字列表转换为如下范围:

[0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15] => ['0->2', '5->5', '7->11', '15->15']

我尝试了以下逻辑:

def findRanges(nums):
    temp = {}
    resArr = []
    for i in nums:
        if i - 1 in temp.keys():
            temp[i - 1] = i
        elif i - 1 in temp.values():
            for key in temp.keys():
                if i - 1 == temp[key]:
                    foundkey = key
            temp[foundkey] = i
        else:
            temp[i] = i

    keylist = list(temp.keys())
    keylist.sort()
    for key in keylist:
        resStr = str(key) + "->" + str(temp[key])
        resArr.append(resStr)

    return resArr


print(findRanges([0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]))
# ['0->2', '5->5', '7->11', '15->15']

它可以很好地合并范围,但是,如我的示例所示,重复了单个元素9,因此它无法合并9。 因此,我的代码返回了输出:['0->2', '5->5', '7->9', '9->11', '15->15'] 在这种情况下我该如何解决?

0 个答案:

没有答案