简体   繁体   中英

How to interpret a list of numbers from a string?

I have number values like:

a="1-5"
b="1,3"
c="1"
d="1,3-5"
e="1-3,5,7-8"
f="0,2-5,7-8,10,14-18"

I want to turn them into full explicit lists of the numbers, like this:

a="1,2,3,4,5"
b="1,3"
c="1"
d="1,3,4,5"
e="1,2,3,5,7,8"
f="0,2,3,4,5,7,8,10,14,15,16,17,18"

Using the re module I can get the numbers:

Like 1 5 in a

But I can't get full range of numbers

ie. 1 2 3 4 5 in a

How can I do this?

I see no need to use regular expressions here:

def expand_ranges(string):
    def expand(start, stop):
        return ','.join(map(str, range(int(start), int(stop) + 1)))
    return ','.join([expand(*d.split('-')) if '-' in d else d for d in string.split(',')])

This

  1. splits the input string on commas.
  2. if there is a dash in the string, split on that dash and expand the range to include the intervening numbers
  3. join the results back with commas.

Demo with each of your test cases:

>>> expand_ranges("1-5")
'1,2,3,4,5'
>>> expand_ranges("1,3")
'1,3'
>>> expand_ranges("1")
'1'
>>> expand_ranges("1,3-5")
'1,3,4,5'
>>> expand_ranges("1-3,5,7-8")
'1,2,3,5,7,8'
>>> expand_ranges("0,2-5,7-8,10,14-18")
'0,2,3,4,5,7,8,10,14,15,16,17,18'

If you're set on regular expressions, you can pass a custom function as the repl argument to re.sub :

>>> import re
>>> def replacer(match):
    start, stop = map(int, match.groups())
    return ','.join(map(str, range(start, stop+1)))

>>> re.sub('(\d+)-(\d+)', replacer, '1-3,5,7-8')
'1,2,3,5,7,8'

You have to treat the range (1 "-" 5) in a special way. Try pythons built in " range " for that.

Best of luck with this exercise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM