python中的排序列表
如果我有一个字符串列表,例如 ["a143.txt", "a9.txt", ]
如何按列表中的数字而不是字符串按升序对其进行排序。即我希望 "a9.txt"
出现在 "a143.txt"
之前,因为 9
143.
.
谢谢。
if I have a list of strings e.g. ["a143.txt", "a9.txt", ]
how can I sort it in ascending order by the numbers in the list, rather than by the string. I.e. I want "a9.txt"
to appear before "a143.txt"
since 9 < 143
.
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这就是所谓的“自然排序”,
来自 http://www.codinghorror.com/blog/2007 /12/sorting-for- humans-natural-sort-order.html
试试这个:
It's called "natural sort order",
From http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
Try this:
使用
list.sort()
并为key
参数提供您自己的函数。将为列表中的每个项目调用您的函数(并传递该项目),并且预计返回将被排序的该项目的版本。请参阅http://wiki.python.org/moin/HowTo/Sorting/#Key_Functions< /a> 了解更多信息。
Use
list.sort()
and provide your own function for thekey
argument. Your function will be called for each item in the list (and passed the item), and is expected to return a version of that item that will be sorted.See http://wiki.python.org/moin/HowTo/Sorting/#Key_Functions for more information.
如果你想完全忽略字符串,那么你应该这样做
If you want to completely disregard the strings, then you should do
更通用的是,如果您希望它也适用于以下文件:a100_32_12(并按数字组排序):
More generic, if you want it to work also for files like: a100_32_12 (and sorting by numeric groups):
list.sort()
已弃用(请参阅 Python.org 操作方法)。sorted(list, key=keyfunc)
更好。list.sort()
is deprecated (see Python.org How-To) .sorted(list, key=keyfunc)
is better.