使用“合并编号”-&引用;(python)
这是python使用“合并编号”-&引用;(python),python,for-loop,Python,For Loop,这是python temp_list=['1','2','3','5','7','8'] temp_list.sort() print temp_list test="" first="" last="" start=0 for i in range(len(temp_list)): if i==0: None else: if (int(temp_list[i-1])+1)==int(temp_list[i]): prin
temp_list=['1','2','3','5','7','8']
temp_list.sort()
print temp_list
test=""
first=""
last=""
start=0
for i in range(len(temp_list)):
if i==0:
None
else:
if (int(temp_list[i-1])+1)==int(temp_list[i]):
print temp_list[i-1]
print temp_list[i]
if start==0:
first=temp_list[i-1]
last=temp_list[i]
start=1;
else:
last=temp_list[i]
if len(temp_list)==i+1:
if start==0:
test+=(temp_list[i-1]+","+temp_list[i])
else:
if len(test)!=0:#add
test+=(","+first+"-"+last)
start=0
else:
test+=(first+"-"+last)
start=0
else:
if start==0:
test+=(temp_list[i-1]+","+temp_list[i])
else:
if len(test)!=0:#add
test+=(","+first+"-"+last)
start=0
else:
test+=(first+"-"+last)
start=0
print test
这是示例代码
此结果->1-35,7,7-8
我要转换以下数字集:
例1)
['1', '2', '3', '5', '7', '8']
->
1-3,5,7-8
例2)
['0', '2', '3', '4', '5', '7', '8']
->
0,2-5,7-8
请帮助我的大脑这应该可以:
def ints_to_ranges(l):
if not l: return ""
l = sorted(set(int(n) for n in l))
ranges = [[l[0], l[0]]]
for n in l[1:]:
if n - 1 == ranges[-1][1]:
ranges[-1][1] += 1
else:
ranges.append([n, n])
return ",".join(r[0] == r[1] and str(r[0]) or "{}-{}".format(*r) for r in ranges)
它的工作原理是删除重复的数字,对它们进行排序,建立一个范围列表,然后格式化它们。例如:
>>> ints_to_ranges(['1', '2', '3', '5', '7', '8'])
'1-3,5,7-8'
>>> ints_to_ranges(['0', '2', '3', '4', '5', '7', '8'])
'0,2-5,7-8'
不直接相关,但您可能需要
temp\u list.sort(key=int)
(否则10将介于1和2之间).我想他想写一个函数,将数字列表转换成字符串,将连续数字压缩成范围。我试了一整天,但没有成功working@user3683061如果我的答案解决了您的问题,您可以通过单击旁边的复选标记进行投票并接受。我喜欢这个解决方案,但只是一个小小的建议:l
作为一个名字有点不清楚。