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

python将list连续元素和非连续元素分开转换为指定字符串
贴吧网友提问
http://tieba.baidu.com/p/3730249293
已知一个由纯数字(顺序由小按大排序)元素组成的列表,比如
li=[1,2,3,4,5,7,8,15,20,21,22,23,24,28]
写一个函数,让它返回如下的字符串
str='1~5,7~8,15,20~24,28'
若数字连续,中间部分用 ~ 省略。

"""
黄哥python远程视频培训班
https://github.com/pythonpeixun/article/blob/master/index.md
黄哥python培训试看视频播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
咨询qq:1465376564
"""


def continuous_str(lst):
    j = 0
    str1 = ''
    for i, item in enumerate(lst):
        if i > 0:
            if lst[i] != lst[i-1] + 1:
                tmp = lst[j:i]
                if len(tmp) == 1:
                    str1 += str(tmp[0]) + ','
                else:
                    str1 += str(tmp[0]) + "~" + str(tmp[-1]) + ','
                j = i
    tmp2 = lst[j:]
    if len(tmp2) == 1:
        str1 += str(tmp2[0]) + ','
    else:
        str1 += str(tmp2[0]) + "~" + str(tmp2[-1]) + ','

    return str1[:-1]

lst = [1, 2, 3, 4, 5, 7, 8, 15, 20, 21, 22, 23, 24, 28]
print continuous_str(lst)

你可能感兴趣的:(python,list,连续元素)