python将list连续元素和非连续元素分开转换为指定字符串

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

obj = {}
def test(nums):
    nums.append(0)
    for item in nums:
        start = obj.get('start', item)
        end = obj.get('end', item)
        if item - end != 1:
            yield "%s"%start if start == end else '%s~%s'%(start, end)
            obj['start'] = item
        obj['end'] = item
lst = [1, 2, 3, 4, 5, 7, 8, 15, 20, 21, 22, 23, 24, 28]
print ','.join([x for x in test(lst)][1:])