mmrs151 mmrs151 - 2 months ago 18
Python Question

How to sort alpha numeric set in python

I have a set

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


After sorting I want it to look like

4 sheets,
12 sheets,
48 sheets,
booklet


Any idea please

Answer

Short and sweet:

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

This version:

  • 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)
  • Will sort on the string part if the quantities are equal

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)