是否有用于字符串自然排序的内置函数? [英] Is there a built in function for string natural sort?

查看:162
本文介绍了是否有用于字符串自然排序的内置函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Python 3.x,我有一个要对其执行自然字母排序的字符串列表.

Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.

自然排序: Windows中文件的排序顺序.

Natural sort: The order by which files in Windows are sorted.

例如,以下列表是自然排序的(我想要的):

For instance, the following list is naturally sorted (what I want):

['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

这是已排序"的上面列表的版本(我所拥有的):

And here's the "sorted" version of the above list (what I have):

['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']

我正在寻找一种类似于第一个函数的排序函数.

I'm looking for a sort function which behaves like the first one.

推荐答案

PyPI上有一个第三方库,名为 natsort (完整披露,我是程序包的作者).对于您的情况,您可以执行以下任一操作:

There is a third party library for this on PyPI called natsort (full disclosure, I am the package's author). For your case, you can do either of the following:

>>> from natsort import natsorted, ns
>>> x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
>>> natsorted(x, key=lambda y: y.lower())
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
>>> natsorted(x, alg=ns.IGNORECASE)  # or alg=ns.IC
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

您应注意,natsort使用通用算法,因此它几乎可以处理您向其抛出的任何输入.如果您想了解为什么选择一个库而不是滚动自己的函数的更多详细信息,请查阅natsort文档的到处都是特殊情况!部分.

You should note that natsort uses a general algorithm so it should work for just about any input that you throw at it. If you want more details on why you might choose a library to do this rather than rolling your own function, check out the natsort documentation's How It Works page, in particular the Special Cases Everywhere! section.

如果需要排序键而不是排序功能,请使用以下任一公式.

If you need a sorting key instead of a sorting function, use either of the below formulas.

>>> from natsort import natsort_keygen, ns
>>> l1 = ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
>>> l2 = l1[:]
>>> natsort_key1 = natsort_keygen(key=lambda y: y.lower())
>>> l1.sort(key=natsort_key1)
>>> l1
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
>>> natsort_key2 = natsort_keygen(alg=ns.IGNORECASE)
>>> l2.sort(key=natsort_key2)
>>> l2
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

这篇关于是否有用于字符串自然排序的内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆