473,404 Members | 2,174 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Code snippet: Natural string sorting


Summary:

Sorts strings in a way that seems natural to humans.
If the
strings contain integers, then the integers are
ordered
numerically. For example, sorts ['Team 11', 'Team 3',
'Team 1']
into the order ['Team 1', 'Team 3', 'Team 11'].

Code:

#
---------------------------------------------------------
# natsort.py: Natural string sorting.
#
---------------------------------------------------------

# By Seo Sanghyeon. Some changes by Connelly Barnes.

def try_int(s):
"Convert to integer if possible."
try: return int(s)
except: return s

def natsort_key(s):
"Used internally to get a tuple by which s is
sorted."
import re
return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
"Natural string comparison, case sensitive."
return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
"Natural string comparison, ignores case."
return natcmp(a.lower(), b.lower())

def natsort(seq, cmp=natcmp):
"In-place natural string sort."
seq.sort(cmp)

def natsorted(seq, cmp=natcmp):
"Returns a copy of seq, sorted by natural string
sort."
import copy
temp = copy.copy(seq)
natsort(temp, cmp)
return temp

Examples:

You can use this code to sort tarball filenames:
natsorted(['ver-1.3.12', 'ver-1.3.3', 'ver-1.2.5', 'ver-1.2.15', 'ver-1.2.3', 'ver-1.2.1'])
['ver-1.2.1', 'ver-1.2.3', 'ver-1.2.5', 'ver-1.2.15',
'ver-1.3.3', 'ver-1.3.12']

Chemical elements:
natsorted(['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6'])
['C1H2', 'C1H4', 'C2H2', 'C2H6', 'C2N', 'C3H6']

Teams:
natsorted(['Team 101', 'Team 58', 'Team 30', 'Team 1'])
['Team 1', 'Team 30', 'Team 58', 'Team 101']

Pass natcasecmp as a second argument for
case-insensitive sorting:
natsorted(['a5', 'A7', 'a15', 'a9', 'A8'],

natcasecmp)
['a5', 'A7', 'A8', 'a9', 'a15']

Enjoy!
Message and source code are in the public domain.


__________________________________
Do you Yahoo!?
Friends. Fun. Try the all-new Yahoo! Messenger.
http://messenger.yahoo.com/

Jul 18 '05 #1
0 1307

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Derek Basch | last post by:
Hello All, I need to sort a list using an unnatural sequence. I have a list like so: foo = print foo.sort()
18
by: Joe Fallon | last post by:
I have some complex logic which is fairly simply to build up into a string. I needed a way to Eval this string and return a Boolean result. This code works fine to achieve that goal. My...
0
by: danieljroot | last post by:
I would like to create a code snippet for a property that automatically names the underlying field with standard naming convention: typing propn string MyProp would expand to: private string...
17
by: Mark | last post by:
I must create a routine that finds tokens in small, arbitrary VB code snippets. For example, it might have to find all occurrences of {Formula} I was thinking that using regular expressions...
6
by: pamela fluente | last post by:
Hi, please find below a very simple code snippet which is giving me the following error: System.Runtime.Serialization.SerializationException was unhandled Message="The constructor to deserialize...
2
by: steve.falzon | last post by:
Hi I've been searching high and low for this info but have been unsuccessful so far. I wonder if anybody knows where I can get a specification for the directives contained within the code...
13
by: Ramon F Herrera | last post by:
I am writing a program that generates source code. See a snippet below. My question is about the use of that growing 'code' variable. Is it efficient? Is is recommended for this case? The code...
3
by: Alpha83 | last post by:
Hi, Is there a code measuring tool that tells you which is more efficient cost-wise. For example, if I were to compare the following two identical code blocks, how do I know, which is more...
1
by: prpradip | last post by:
In my application ListView is inside panel (XP theme enable), item text in the ListView control overlaps other items in small icon view. The items are drawn as if aligned to a grid and this causes...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.