你想使用
natural sort:
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)]
用法示例:
>>> list1 = ["1", "100A", "342B", "2C", "132", "36", "302F"]
>>> list1.sort(key=natural_sort_key)
>>> list1
['1', '2C', '36', '100A', '132', '302F', '342B']
这通过将元素拆分为分隔数字并将它们作为整数而不是字符串进行比较的列表来实现:
>>> natural_sort_key("100A")
['', 100, 'a']
>>> natural_sort_key("342B")
['', 342, 'b']
请注意,这只适用于Python3,如果您始终将int与int和字符串与字符串进行比较,否则会出现TypeError:unorderable types exception.