python中怎么表示数字范围_在Python中解释数字范围

使用来自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('-')]

你可能感兴趣的:(python中怎么表示数字范围)