关于在python中排序:在python中排序 – 如何对包含字母数字值的列表进行排序?

Sorting in python - how to sort a list containing alphanumeric values?

我有一个列表,包含如下详细信息:

1
list1 = ["1","100A","342B","2C","132","36","302F"]

现在,我要对该列表进行排序,使值按以下顺序排列:

1
list1 = ["1","2C","36","100A","132","302F","342B"]

显然,仅仅做EDOCX1[0]并不能给出正确的答案。-它给出:

1
list1 = ["1","100A","132","2C","36","302F","342B"]

我假设这是因为Python直接将所有这些作为字符串处理。但是,我想首先根据它们的数值,然后根据数字后面的字符对它们进行排序。

如何继续?

非常感谢:)


您要使用自然排序:

1
2
3
4
5
6
import re

_nsre = re.compile('([0-9]+)')
def natural_sort_key(s):
    return [int(text) if text.isdigit() else text.lower()
            for text in re.split(_nsre, s)]

示例用法:

1
2
3
4
>>> list1 = ["1","100A","342B","2C","132","36","302F"]
>>> list1.sort(key=natural_sort_key)
>>> list1
['1', '2C', '36', '100A', '132', '302F', '342B']

此函数将元素拆分为列表,分离出数字,并将其作为整数而不是字符串进行比较:

1
2
3
4
>>> natural_sort_key("100A")
['', 100, 'a']
>>> natural_sort_key("342B")
['', 342, 'b']

注意,这只在python3中有效,如果您总是比较int与int,字符串与字符串,否则会得到TypeError: unorderable types异常。


嗯,你必须先找到一种方法把你的字符串转换成数字。例如

1
2
3
import re
def convert(str):
    return int("".join(re.findall("\d*", str)))

然后将其用作排序键:

1
list1.sort(key=convert)