6

I have "2,5,7-9,12" string.

I want to get [2, 5, 7, 8, 9, 12] list from it.

Is there any built-in function for it in python?

Thanks.

UPD. I suppose, the straight answer is No. Anyway, thanks for your "snippets". Using one, suggested by Sven Marnach.

disfated
  • 10,633
  • 12
  • 39
  • 50
  • A duplicate. http://stackoverflow.com/questions/712460/interpreting-number-ranges-in-python – S.Lott Apr 18 '11 at 17:16

6 Answers6

15
s = "2,5,7-9,12"
ranges = (x.split("-") for x in s.split(","))
print [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)]

prints

[2, 5, 7, 8, 9, 12]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
5
s = "2,5,7-9,12"
result = list()

for item in s.split(','):
    if '-' in item:
        x,y = item.split('-')
        result.extend(range(int(x), int(y)+1))
    else:
        result.append(int(item))

print result
2

This version handles arbitrary whitespace, overlapping ranges, out-of-order ranges, and negative integers:

from itertools import chain

def group_to_range(group):
  group = ''.join(group.split())
  sign, g = ('-', group[1:]) if group.startswith('-') else ('', group)
  r = g.split('-', 1)
  r[0] = sign + r[0]
  r = sorted(int(__) for __ in r)
  return range(r[0], 1 + r[-1])

def rangeexpand(txt):
  ranges = chain.from_iterable(group_to_range(__) for __ in txt.split(','))
  return sorted(set(ranges))


>>> rangeexpand('-6,-3--1,3-5,7-11,14,15,17-20')
[-6, -3, -2, -1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
>>> rangeexpand('1-4,6,3-2, 11, 8 - 12,5,14-14')
[1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 14]
Sean Summers
  • 2,514
  • 19
  • 26
2

Not that I'm aware of, but you can easily make your own:

  1. Create a results list.
  2. Split strings by , and start iterating over the result.
    1. If the current string contains a - append a range to the list.
    2. If the current string is a number, append it to the list.
    3. Else return an error.
  3. Return the list.
orlp
  • 112,504
  • 36
  • 218
  • 315
2

I am not aware of any built-in function that would do that. The following isn't particularly elegant, but gets the job done:

s = "2,5,7-9,12"
ret = []
for tok in s.split(","):
  val = map(int, tok.split("-"))
  if len(val) == 1:
    ret += val
  else:
    ret += range(val[0], val[1] + 1)
print ret

One area where this solution may need work is the handling of negative numbers (it is not entirely clear from your question whether negative numbers can appear in the input).

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

I would define function:

def make_range(s):
    out = []
    s = s.split(',')
    for n in s:
        if '-' in n:
            n = n.split('-')
            for i in range(int(n[0]), int(n[1]) + 1):
                out.append(i)
        else:
            out.append(int(n))
    return out

print make_range("2,5,7-9,12")
#output [2, 5, 7, 8, 9, 12]
Anatolij
  • 597
  • 3
  • 11