Reputation: 29
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)
Right now it is outputting:
((((((1, '-', 7), ',', 9), '-', 12), ',', 14), '-', 19), ',', 300) and I want it to be 1-7,9-12,14-19,300
Upvotes: 0
Views: 301
Reputation: 8790
The following approach seems to be working. I was trying to make something that only iterated through the data once:
c = 0
result = ''
current = None
run = False
while c < len(line):
if current == None:
result += f'{line[c]}'
elif line[c] - current == 1:
run = True
if c == len(line) - 1:
result += f'-{line[c]}'
elif run:
result += f'-{current},{line[c]}'
run = False
else:
result += f',{line[c]}'
current = line[c]
c += 1
print(result)
# 1-7,9-12,14-19,300
The first if
checks if no numbers have been seen, i.e. only for the first number. The second if
notes that the current integer is one greater than the previous, also handling the when the end of the line
is reached and is continuing a sequence. The third notes that a sequence has been broken, and adds the output as such. The last else
block adds the current value following a non-sequence.
Upvotes: 1
Reputation: 4980
Would this helps you: (lastly, you could modify the final concatenation as you like in terms of format...)
>>> line = [1,2,3,4,5,6,7,9,10,11,12,14,15,16,17,18,19,300]
>>> starts = [x for x in line if x-1 not in line]
>>> ends = [y for y in line if y+1 not in line]
>>> ranges = list((a,b) for a, b in zip(starts, ends))
>>> ranges
[(1, 7), (9, 12), (14, 19), (300, 300)]
>>> results = [str(a)+'-'+str(b) for a, b in ranges]
Upvotes: 1
Reputation: 222
try this
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 = f'{FormatDesignators} - {line[i - 1]},'
FormatDesignators = f'{FormatDesignators} {line[i]}'
GroupCount = 0
else:
GroupCount = GroupCount + 1
print(FormatDesignators)
if GroupCount >= 1:
FormatDesignators = f'{FormatDesignators} - {line[i]},'
print (FormatDesignators)
Upvotes: 1