如何通过从点拆分来剪切列表的子字符串,例如 s[0][i:j]?

How to cut substrings of a list like from s[0][i:j] by splitting from dots?

抱歉,用英语告诉我这件事很复杂。这是我的问题。我有这个列表:

s=["2.11", "4.7.0", "1.3", "2.2", "0.1", "1.2.5", "1.3.1", "2.7"]

我希望这些数字按从小到大的顺序排列。但不是数学上的,不完全是。对于版本号的概念。

将它们视为版本号。不是普通的数学。对于普通数学,2.2>2.11 但对于程序版本号概念,它是 2.11>2.2 所以我需要以某种方式对它们进行排序。我首先想到的是这个。也许从那里得到 11、7、3、2 个数字,这些数字是从点中分离出来的。然后比较它们,问题是如何把它们弄出来?我尝试了 Whosebug 的各种解决方案。例如 2.11 的 11 是这样的:

print(s[0][2:len(s[0])]) # prints 11

因为这个列表实际上是像你一样的二维数组,所以很多解决方案都不适合我。请帮忙。或者我错过了什么?有更简单的方法吗?

预期输出如下。认为这个 returns 来自一个函数:

0.1,1.2.5,1.3,1.3.1,2.2,2.7,2.11,4.7

使用:

s=["2.11", "4.7.0", "1.3", "2.2", "0.1", "1.2.5", "1.3.1", "2.7"]
res = sorted(s, key=lambda x: tuple(map(int, x.split("."))))
print(res)

输出

['0.1', '1.2.5', '1.3', '1.3.1', '2.2', '2.7', '2.11', '4.7.0']

想法是使用 sorted 的关键参数比较字符串,来自文档(强调我的):

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

在这种情况下,关键参数将字符串拆分为 ".",并将每个子字符串转换为整数,例如:

"0.1" -> (0, 1)
"2.2" -> (2, 2)
"2.11" -> (2, 11)

作为替代用途:

res = sorted(s, key=lambda x: [int(xi) for xi in x.split(".")])

here you can find more ideas for key parameter of sorted (how to compare version numbers in Python). If the version is PEP440 compliant you could use packaging.version.parse中:

from packaging.version import parse

s = ["2.11", "4.7.0", "1.3", "2.2", "0.1", "1.2.5", "1.3.1", "2.7"]
res = sorted(s, key=parse)
print(res)

输出

['0.1', '1.2.5', '1.3', '1.3.1', '2.2', '2.7', '2.11', '4.7.0']

所以这个应该可以工作

# as version numbers, so 2.7.2 is less than 2.7.11 for example.
s = ["2.11", "4.7.0", "1.3", "2.2", "0.1", "1.2.5", "1.3.1", "2.7"]

# sort the list of versions numbers
s.sort(key=lambda x: list(map(int, x.split('.'))))
print(s)

从 python>=3.8 开始,我认为 map returns 是一个迭代器,因此我们需要手动将其转换为列表

一种方法使用 distutils.version.LooseVersion.

如果它们类似版本,则将它们作为版本处理。

from distutils.version import LooseVersion

sorted(s, key=LooseVersion)

输出:

['0.1', '1.2.5', '1.3', '1.3.1', '2.2', '2.7', '2.11', '4.7.0']