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']