python - 如何在python中对字母数字集进行排序

标签 python sorting

我有一套

set(['booklet', '4 sheets', '48 sheets', '12 sheets'])

排序后我希望它看起来像

4 sheets,
12 sheets,
48 sheets,
booklet

有什么建议

最佳答案

Jeff Atwood讨论自然排序,并举例说明在 Python 中实现它的一种方法。这是我的变化:

import re 

def sorted_nicely( l ): 
    """ Sort the given iterable in the way that humans expect.""" 
    convert = lambda text: int(text) if text.isdigit() else text 
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] 
    return sorted(l, key = alphanum_key)

这样使用:

s = set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
for x in sorted_nicely(s):
    print(x)

输出:

4 sheets
12 sheets
48 sheets
booklet

这种方法的一个优点是它不仅仅在字符串用空格分隔时起作用。它也适用于其他分隔符,例如版本号中的句点(例如 1.9.1 在 1.10.0 之前)。

关于python - 如何在python中对字母数字集进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2669059/

相关文章:

Python Plotly 用文本注释多个变量

python - 复杂排序字典到排序列表

c# - 为什么默认的字符串比较器无法保持传递一致性?

c++ - 双向链表上的快速排序

python - 散点图抛出类型错误

python - 幻像类型错误(Python 3.3)

python - 如何从一堆图像中裁剪具有不同位置的相同大小的图像 block ?

Python-更改列表列表中的元素

Python 对数组进行排序

java - 将值存储在列表中然后使用集合对它们进行排序不起作用