Python:获取两个虚线数字之间的范围

时间:2015-02-28 01:27:23

标签: python

我试图获得两个虚线数字之间的数字范围,如2.1.0和2.1.3。

我的要求是前两个数字必须相同(所以不是2.1.0到2.2.0)

我想要的是:

['2.1.0', '2.1.1', '2.1.2', '2.1.3']

这是我尝试过的,但它确实有效,但我想知道是否有更好的方法。

start = "2.1.0"
end = "2.1.3"

def get_dotted_range(start,end):
    start_parts = start.split(".")
    end_parts = end.split(".")
    # ensure the versions have the same number of dotted sections
    if len(start_parts) != len(end_parts):
        return False
    # ensure first 2 numbers are the same
    for i in range(0,len(start_parts[:-1])):
        if start_parts[i] != end_parts[i]:
            # part is different betwen start and end!
            return False
    new_parts = []
    # ensure last digit end is higher than start
    if int(end_parts[-1]) >= int(start_parts[-1]):
        # append the version to the return list
        for i in range(int(start_parts[-1]),int(end_parts[-1]) + 1):
            new_parts.append("%s.%s.%s" % (start_parts[0],start_parts[1],i))
    else:
        return False    # end is lower than start

    return new_parts

4 个答案:

答案 0 :(得分:2)

start = "2.1.0"
end = "2.1.3"

startFirst, startMiddle, startLast = map(int, start.split("."))
_, _, endLast = map(int, end.split("."))

dottedRange = [".".join(map(str, [startFirst, startMiddle, x])) 
               for x in range(startLast, 1+endLast)]

答案 1 :(得分:1)

start = "2.1.0"
end = "2.1.3"

# split once to get last value
s_spl, e_spl = start.rsplit(".",1), end.rsplit(".",1)
# get first part of string to join up later
pre = s_spl[0]
# make sure first two parts are identical
if pre == e_spl[0]:     
    # loop in range from last element of start 
    # up to and including last element of end
    out = ["{}.{}".format(pre, i) for i in range(int(s_spl[1]), int(e_spl[1]) + 1)]
    print(out)

print(out)
['2.1.0', '2.1.1', '2.1.2', '2.1.3']

因此在函数中我们会返回一个列表或False:

def get_dotted_range(start,end):
    s_spl, e_spl = start.rsplit(".", 1), end.rsplit(".", 1)
    pre = s_spl[0]
    if pre == e_spl[0]:
        return  ["{}.{}".format(pre, i) for i in range(int(s_spl[1]), int(e_spl[1])+1)]
    return  False

您还应该考虑用户输入不能转换为int的错误数据,格式不正确或者输入空字符串以便得到错误索引等的情况......

def get_dotted_range(start, end):
    try:
        s_spl, e_spl = start.rsplit(".", 1), end.rsplit(".", 1)
        if s_spl[0] == e_spl[0]:
            pre = s_spl[0]
            return ["{}.{}".format(pre, i) for i in range(int(s_spl[1]), int(e_spl[1]) + 1)]
    except ValueError as e:
        return "{}: Digit expected".format(e)
    except IndexError as e:
        return "{}: Input format should be d.d.d ".format(e)
    return False

在其他情况下,您可能希望捕获,例如当用户输入开始和结束时,最终返回空。

答案 2 :(得分:1)

一种方式:

def get_dotted_range(start, end):
  sparts = start.split('.')
  eparts = end.split('.')

  prefix = '.'.join(sparts[0:-1])

  slast = int(sparts[-1]) 
  elast = int(eparts[-1]) 

  return [prefix + '.' + str(i) for i in range(slast, elast + 1)] 

print(get_dotted_range('2.1.0', '2.1.3'))
print(get_dotted_range('2.1.9', '2.1.12'))

结果:

['2.1.0', '2.1.1', '2.1.2', '2.1.3']
['2.1.9', '2.1.10', '2.1.11', '2.1.12']

答案 3 :(得分:1)

start = "2.1.0"
end   = "2.1.3"

def get_dotted_range(start, end):
    # break into number-pieces
    start = start.split(".")
    end   = end  .split(".")
    # remove last number from each
    x = int(start.pop())
    y = int(end  .pop())
    # make sure start and end have the same number of sections
    #   and all but the last number is the same
    if start != end:
        return []
    else:
        head = ".".join(start) + "."
        return [head + str(i) for i in range(x, y + 1)]

然后

In [67]: get_dotted_range(start, end)
Out[67]: ['2.1.0', '2.1.1', '2.1.2', '2.1.3']