Last active
December 18, 2015 18:09
-
-
Save nmpeterson/5823235 to your computer and use it in GitHub Desktop.
A function to convert a list of integers into a string of ranges of consecutive values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def list_to_ranges(in_list): | |
''' Convert a list of integers into a string of ranges of consecutive values. ''' | |
l = in_list[:] | |
l.sort() | |
range_str = str(l[0]) | |
for i in xrange(1,len(l)-1): # Handle first & last separately | |
if l[i] == l[i-1]+1 and l[i] == l[i+1]-1: | |
pass | |
elif l[i] != l[i-1]+1: | |
range_str += ', ' + str(l[i]) | |
else: | |
range_str += '-' + str(l[i]) | |
if len(l) > 1: | |
if l[-1] == l[-2]+1: | |
range_str += '-' + str(l[-1]) | |
else: | |
range_str += ', ' + str(l[-1]) | |
del l | |
return range_str | |
# Example call: | |
list_to_ranges([1, 2, 3, 4, 5, 7, 8, 9, 21, 22, 23]) #=> '1-5, 7-9, 21-23' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment