Python 文件名排序(排了sorted排不了的正是我natsorted哒!)
2021/7/2 11:22:07
本文主要是介绍Python 文件名排序(排了sorted排不了的正是我natsorted哒!),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Python 文件名排序
使用natsort包的natsorted方法
from natsort import natsorted
官方说明中有提到
natsort provides a function natsorted that helps sort lists “naturally” (“naturally” is rather ill-defined, but in general it means sorting based on meaning and not computer code point).
natsort 提供一个 natsorted 函数,这个函数可以自然的排列列表(“自然”的定义是不明确的,但是他会根据一定的含义进行排序,而不只是根据计算机代码)
>> from natsort import natsorted >> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >> natsorted(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in']
Note: natsorted is designed to be a drop-in replacement for the built-in sorted function. Like sorted, natsorted does not sort in-place. To sort a list and assign the output to the same variable, you must explicitly assign the output to a variable
注意:natsorted 被设计为内置 sorted 函数的替代品。像 sorted 一样,natsorted 不会就地排序。要对列表进行排序并将输出分配给同一个变量,您必须将输出显式分配给一个变量
>> a = ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >> natsorted(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in'] >> print(a) # 'a'并没有被排序;"natsorted"只是简单的返回了一个列表 ['2 ft 7 in', '1 ft 5 in', '10 ft 2 in', '2 ft 11 in', '7 ft 6 in'] >> a = natsorted(a) # 现在'a'将会被排序,因为将排序过的'a'赋值给了'a' >> print(a) ['1 ft 5 in', '2 ft 7 in', '2 ft 11 in', '7 ft 6 in', '10 ft 2 in']
这篇关于Python 文件名排序(排了sorted排不了的正是我natsorted哒!)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python