My script needs to take an option followed by a list of pages, specified as comma-separated list of ranges, and to process the expanded list of pages. So, for instance,
script.py -a 2,4-6,9,10-13
should get the list
[2, 4, 5, 6, 9, 10, 11, 12, 13]
to work with. Currently I am doing this:
import argparse
def getList(argument):
ranges = list(argument.split(","))
newRange = []
for theRange in ranges:
subRange = list(map(int, theRange.split("-")))
if (len(subRange) > 1):
newRange.extend(range(subRange[0], subRange[1] + 1))
else:
newRange.extend(subRange)
newRange.sort()
return newRange
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--pages", type=getList, dest="pages", default=[], help="pages to process")
args = parser.parse_args()
and it works but I'm relatively new to this Python thing and was wondering if there is a better way to do it?
Edit: I fail to see why it was marked as a duplicate question. None of the answers to the questions it was marked as a duplicate of does exactly what I have described above. The idea is not to process a simple list of space- or comma-delimited arguments but something more complex - a list of ranges that have to be expanded.