python Converts the list continuous and non-contiguous elements to the specified string
Bar User Questions
http://tieba.baidu.com/p/3730249293
a list of elements that are known to consist of a pure number (ordered by a small size), such as
li=[1,2,3,4,5,7,8,15,20,21,22,23,24,28]
write a function so that it returns the following string
str= ' 1~5,7~8,15,20~24,28 '
If the number is continuous, the middle part is omitted by ~.
"""
Huanggo python Remote video training course
Https://github.com/pythonpeixun/article/blob/master/index.md
Huanggo python Training preview video playback address
Https://github.com/pythonpeixun/article/blob/master/python_shiping.md
Consulting 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, , (+)
print continuous_str (LST)
Python converts the list continuous and non-contiguous elements to the specified string