Python 有个默认的排序函数 sorted,其对字符串的排序是按照 Unicode 编码的大小来的,例如:
>>> x = ['1', '2', '11', '33']
>>> sorted(x)
['1', '11', '2', '33']
但实际我们想要的结果可能是按照数字大小排列的,该如何实现呢?这里有个名为 natsort
的第三方库给我们提供了解决方案。
pip install natsort
用法
>>> from natsort import natsorted
>>> x = ['1', '2', '11', '33']
>>> natsorted(x)
['1', '2', '11', '33']
提示
其实库的名字也很好记。natsort
可拆分为 nat
和 sort
,nat
是单词 nature
的前三个字母,表示自然的意思,sort
就是排序。
https://pypi.org/project/natsort/