打印算法的页面范围

时间:2010-11-22 17:39:59

标签: python algorithm

某些打印对话框提供了指定要打印的页面(和页面范围)的选项。

1-10, 3, 4, 23-47

那里有配方/算法吗?

3 个答案:

答案 0 :(得分:6)

def parse_range(astr):
    result=set()
    for part in astr.split(','):
        x=part.split('-')
        result.update(range(int(x[0]),int(x[-1])+1))
    return sorted(result)

print(parse_range('1-10, 3, 4, 23-47'))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]

答案 1 :(得分:2)

几年后,我创建了一个提供PageRange对象的python包。它位于https://github.com/taylorzr/PageRange的github上,https://pypi.python.org/pypi/PageRange/上的pypi上:

pip install PageRange

用法:

from pagerange import PageRange

page_range = PageRange("1-10, 3, 4, 23-47") #-> PageRange("1-10,23-47")
page_range.range #-> "1-10,23-47"
page_range.pages #-> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]

page_range.add_page(48)
page_range.range #-> "1-10,23-47"

答案 2 :(得分:-1)

你在找这个吗?

outer= text.split(",")
dashes= [ x.partition('-') for x in outer ]
ranges= [ (x,z) if y == '-' else (x,x) for x,y,z in dashes ]
[ (int(x),int(y)) for x,y in ranges ]