2017-10-05 68 views
1

是否有可能在python中以某种方式减去使用多个小数位(如在版本号中)。python减去多个小数位

例如,

8.0.18试图找到以前版本的8.0.17

任何方式或方法减去1得到8.0.17?

我想到的正则表达式,并拔出18和减1,然后让自己从8.0的变量。并加入17回吧:),像这样

version_found = "8.0.18" 
version = re.search('^\d.\d\d.(\d\d)$', version_found).group(1) 
prev_version = int(version) - 1 

所以prev_version将结束是17,那么我可以重新转换为字符串,并把它到8.0。 但想知道是否有某种方法我不知道或不考虑?谢谢

+3

应该如何减去'8.10.0'? – RomanPerekhrest

+0

[在Python中增加版本号]的可能重复(https://stackoverflow.com/questions/26868137/incrementing-version-numbers-in-python),哦,我的坏它是'递减',但可能有关-_- – davedwards

+0

可能有用的图书馆[semantic_version](https://pypi.python.org/pypi/semantic_version) – davedwards

回答

3

这里是一个小小的剧本我写的,它应该是很容易在你的代码来实现:

#!/usr/bin/env python3.6 

version = "8.0.18" 
version = version.split(".") 
if int(version[-1]) > 0: 
    version[-1] = str(int(version[-1]) - 1) 
    version = '.'.join(version) 
    print(version) 
else: 
    print("Error, version number ended in a zero!") 

这是通过分割字符串转换成每个时期的列表,导致["8", "0", "18"]。然后通过访问索引-1获取列表中的最后一个元素。然后,我们从该索引的值中减去1,并将其分配回相同的索引。最后,将列表加入一个字符串中,每个元素之间有句点,然后打印结果。

0

我认为这样做的最好方法是计算字符串中的句点数,然后在希望减少的特定时间段内分割文本。然后,您必须将字符串转换为整数,从该整数中减1,然后将其读入版本号。

有几种方法可以做到这一点,但多数民众赞成我这样做的方式。同时将它保存在一个函数中,以便在不同的时间点多次调用它。

0

基于Steampunkery

version = "6.4.2" 
nums = version.split(".") 

skip = 0 # skip from right, e.g. to go directly to 6.3.2, skip=1 

for ind in range(skip,len(nums)): 
    curr_num = nums[-1-ind] 
    if int(curr_num) > 0: 
     nums[-1-ind] = str(int(curr_num) - 1) 
     break 
    else: 
     nums[-1-ind] = "x" 

oldversion = '.'.join(nums) 
print(oldversion)  

样品输出:

8.2.0 --> 8.1.x 
8.2.1 --> 8.2.0 
8.0.0 --> 7.x.x 
0.0.0 --> x.x.x 
8.2.0 --> 8.1.0 (with skip=1) 
+0

没有冒犯,但这是一个非常艰难的阅读。为了便于阅读,您可能需要将一些位分隔到不同的行上。 – Steampunkery

+0

@Steampunkery没错,但是我们想到了同样的想法。没有解决:**它应该如何减去8.10.0?**然而 –

+0

真的,它可能不会减去8.10.0,但你的答案确实完成了工作,只是检查:) – Steampunkery

0
version = "8.0.18" 
index = version.rindex(".") + 1 
version = version[:index] + str(int(version[index:])-1) 

只需使用RINDEX找到你的最后期限。 然后,将其后的所有内容转换为数字,减去一个,将其重新转换为字符串,然后完成。

如果您想要使用除上一个版本号以外的任何值,这会变得更加复杂。您必须从每次返回的位置进行rindex。例如,到之后的“第二次从去年”更改值(即第一)小数点后一位,它变得丑陋:

start_index = version.rindex(".") 
for _ in range(1,1): 
    end_index = start_index 
    start_index = version.rindex(".", end=end_index) 

version = version[:start_index+1] + 
    str(int(version[start_index+1:end_index])) + 
    version[end_index:] 
0
lst = version.split('.')   # make a list from individual parts 

last_part = lst.pop()    # returns the last element, deleting it from the list 
last_part = int(last_part) - 1  # converts to an integer and decrements it 
last_part = str(last_part)   # and converts back to string 

lst.append(last_part)    # appends it back (now decremented) 

version = '.'.join(lst)    # convert lst back to string with period as delimiter