line = [1,2,3,4,5,6,7,9,10,11,12,14,15,16,17,18,19,300]
GroupCount = 0
FormatDesignators =line[0]
for i in range(1 ,len(line)):
if line[i] != line[i - 1] + 1:
if GroupCount >= 1:
FormatDesignators = FormatDesignators,'-', line[i - 1]
FormatDesignators = FormatDesignators,',',line[i]
GroupCount = 0
else:
GroupCount = GroupCount + 1
print(FormatDesignators)
if GroupCount >= 1:
FormatDesignators = FormatDesignators,"-",line[i]
print (FormatDesignators)
现在它正在输出:
((((((1, '-', 7), ',', 9), '-', 12), ',', 14), '-', 19), ',', 300) and I want it to be 1-7,9-12,14-19,300
这对您有帮助吗:(最后,您可以根据自己的喜好在格式方面修改最终的连接…)
以下方法似乎有效。我试图做一些只在数据中迭代一次的东西:
第一个
if
检查是否未看到任何数字,即仅检查第一个数字。第二个if
注意到当前整数比前一个大一,当到达line
的末尾并继续一个序列时也会处理。第三个注意到一个序列已被破坏,并添加输出。最后一个else
块在非序列之后添加当前值试试这个
相关问题 更多 >
编程相关推荐