Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort alpha numeric set in python

Tags:

python

sorting

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

like image 281
mmrs151 Avatar asked Apr 19 '10 16:04

mmrs151


People also ask

How do you sort alpha numeric?

Alphanumeric ordering is done using the current language sort order on the client machine as defined by the operating system (i.e. Windows). The user requests the sort by clicking on the column header. A grid must have column headings in order to be sorted by the user.

How do you sort a set alphabetically in Python?

To sort a list alphabetically in Python, use the sorted() function. The sorted() function sorts the given iterable object in a specific order, which is either ascending or descending. The sorted(iterable, key=None) method takes an optional key that specifies how to sort.

How do you sort a set in Python?

To sort the values of the set in Python, use the sorted() method. The sorted() is a built-in method that returns the new sorted list from the items in iterable. The sorted() method takes two optional arguments, which must be defined as keyword arguments. The sorted() method is giving you a list, not a set.


1 Answers

Jeff Atwood talks about natural sort and gives an example of one way to do it in Python. Here is my variation on it:

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) 

Use like this:

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

Output:

4 sheets 12 sheets 48 sheets booklet 

One advantage of this method is that it doesn't just work when the strings are separated by spaces. It will also work for other separators such as the period in version numbers (for example 1.9.1 comes before 1.10.0).

like image 74
Mark Byers Avatar answered Oct 10 '22 14:10

Mark Byers