【Python】自然排序(natsort)
责任编辑:梦想飞行     时间:2023-11-08     来源:转载于:https://blog.csdn.net/qq_42951560/article/details/124362424
责任编辑:梦想飞行
时间:2023-11-08  来源:转载于:https://blog.csdn.net/qq_42951560/article/details/124362424
分类: 技术分享
浏览量: 140

image.png

引言
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://blog.csdn.net/qq_42951560/article/details/124362424

回复:

Copyright © 2021 .长沙麦涛网络科技有限公司 All rights reserved. 湘ICP备20015126号-2
联系我们