標籤:python
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連續元素和非連續元素分開轉換為指定字串