Parsing numeric ranges
Alain Ketterlin
alain at dpt-info.u-strasbg.fr
Fri Feb 25 04:44:13 EST 2011
Seldon <seldon at katamail.it> writes:
> I have to convert integer ranges expressed in a popular "compact"
> notation (e.g. 2, 5-7, 20-22, 41) to a the actual set of numbers (i.e.
> 2,5,7,20,21,22,41).
What form does the input have? Are they strings, or some other
representation?
> Is there any library for doing such kind of things or I have to write
> it from scratch ?
What kind of result do you need? An explicit list? A generator?
Here is a naive solution where the input is a list of strings and the
result a generator:
def values(l):
for item in l:
bounds = item.split('-')
if len(bounds) == 1:
yield int(bounds[0])
elif len(bounds) == 2:
for v in range(int(bounds[0]),1+int(bounds[1])):
yield v
else:
pass # ignore, or throw, or...
# Use as in:
for x in values(["1","2-3","4-10"]):
print x
-- Alain.
More information about the Python-list
mailing list