如何对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中不起作用)
    • 它不对sorted使用cmp参数(在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 ',\n'.join(r)