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
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With