在 Pylons 网络应用程序中,我需要使用诸如“<3, 45, 46, 48-51, 77”之类的字符串并创建一个整数列表(实际上是对象的 ID)以进行搜索。
关于如何做到这一点有什么建议吗?我是 Python 的新手,我还没有发现任何可以帮助解决此类问题的东西。
列表将是:[1, 2, 3, 45, 46, 48, 49, 50, 51, 77]
最佳答案
使用来自 here 的 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)
这是示例运行的输出:
$ 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])
关于python - 在 Python 中解释数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/712460/