Eri*_*Red 4 python numeric-ranges
在Pylons webapp中,我需要使用诸如"<3,45,46,48-51,77"之类的字符串,并创建要搜索的整数列表(实际上是对象的ID).
有关如何做到这一点的任何建议?我是Python的新手,我没有找到任何有助于这种事情的东西.
名单将是:[1,2,3,45,46,48,49,50,51,77]
Joh*_*ood 12
从这里使用parseIntSet
我也喜欢最后评论中的pyparsing实现.
此处已修改parseIntSet以处理"<3"类型的条目,并且仅在无效字符串中吐出(如果有).
#! /usr/local/bin/python
import sys
import os
# return a set of selected values when a string in the form:
# 1-4,6
# would return:
# 1,2,3,4,6
# as expected...
def parseIntSet(nputstr=""):
selection = set()
invalid = set()
# tokens are comma seperated values
tokens = [x.strip() for x in nputstr.split(',')]
for i in tokens:
if len(i) > 0:
if i[:1] == "<":
i = "1-%s"%(i[1:])
try:
# typically tokens are plain old integers
selection.add(int(i))
except:
# if not, then it might be a range
try:
token = [int(k.strip()) for k in i.split('-')]
if len(token) > 1:
token.sort()
# we have items seperated by a dash
# try to build a valid range
first = token[0]
last = token[len(token)-1]
for x in range(first, last+1):
selection.add(x)
except:
# not an int and not a range...
invalid.add(i)
# Report invalid tokens before returning valid selection
if len(invalid) > 0:
print "Invalid set: " + str(invalid)
return selection
# end parseIntSet
print 'Generate a list of selected items!'
nputstr = raw_input('Enter a list of items: ')
selection = parseIntSet(nputstr)
print 'Your selection is: '
print str(selection)
Run Code Online (Sandbox Code Playgroud)
这是样本运行的输出:
$ python qq.py
Generate a list of selected items!
Enter a list of items: <3, 45, 46, 48-51, 77
Your selection is:
set([1, 2, 3, 45, 46, 77, 48, 49, 50, 51])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3980 次 |
| 最近记录: |