- 如果有一个版本号的list:
如 version = ['2.0.1', '1.0.2', '1.0.21', '2,2.9', '1.2.11']
要求:要对version大小进行排序,获得最大的版本号(2.2.9)。
思路:可以转换成数字型tuple,再对其排序。
>>> version = ['2.0.1', '1.0.2', '1.0.21', '2.2.9', '1.2.11']
>>> sorted(version, key=lambda x:tuple(int(v) for v in x.split(".")))
['1.0.2', '1.0.21', '1.2.11', '2.0.1', '2.2.9']
- 如果版本号带上前缀,key函数则会异常
>>> version = ['v2.0.1', 'v1.0.2', 'v1.0.21', 'v2.2.9', 'v1.2.11']
>>> version.sort(key=lambda x:tuple(int(v) for v in x.split(".")))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
File "<stdin>", line 1, in <genexpr>
ValueError: invalid literal for int() with base 10: 'v2'
原因:转换为tuple时将之数字化存在字符,可以稍微修改以适应前缀。
>>> version = ['v2.0.1', 'v1.0.2', 'v1.0.21', 'v2.2.9', 'v1.2.11']
>>> sorted(version, key=lambda x:tuple(int(v) for v in x.replace('v', '').split(".")))
['v1.0.2', 'v1.0.21', 'v1.2.11', 'v2.0.1', 'v2.2.9']