我正在尝试获取两个点分数字之间的数字范围,例如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
python大神给出的解决方案
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']