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

问题描述:

我有一套

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

排序后我希望它看起来像

After sorting I want it to look like

4 sheets,
12 sheets,
48 sheets,
booklet

请有任何想法

简短而甜蜜:

sorted(data, key=lambda item: (int(item.partition(' ')[0])
                               if item[0].isdigit() else float('inf'), item))

这个版本:

  • 适用于 Python 2 和 Python 3,因为:
    • 它不假设您比较字符串和整数(这在 Python 3 中不起作用)
    • 它不使用 cmp 参数来sorted(Python 3 中不存在)
    • Works in Python 2 and Python 3, because:
      • It does not assume you compare strings and integers (which won't work in Python 3)
      • It doesn't use the cmp parameter to sorted (which doesn't exist in Python 3)

      如果您想要完全按照示例中所述的打印输出,则:

      If you want printed output exactly as described in your example, then:

      data = set(['booklet', '4 sheets', '48 sheets', '12 sheets'])
      r = sorted(data, key=lambda item: (int(item.partition(' ')[0])
                                         if item[0].isdigit() else float('inf'), item))
      print ',
      '.join(r)