python - 在 Python 中解释数字范围

标签 python numeric-ranges

在 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/

相关文章:

python - 用 matplotlib 表示体素

python - 从 Python 中的模块导入特定函数的要点

xml - SoapUI GroovyScript 断言在预期值的 (+ 或 -) 0.05 范围内

c++ - 保护 C++ 变量免于溢出?如果值小于任何数据类型的 UpperBound

perl - 将数字值/范围字符串转换为实际值

python - 我可以要求一些很棒的个性化Python IDE 的屏幕截图吗?

python - 将 matplotlib 安装到 pypy

python - 无法从最后一个 elif 获得输出

javascript - 优化代码以将数字 1 - 25 统一映射到 5 种颜色

javascript - 正则表达式匹配 2-10,但不匹配 99