sorting on IP addresses

chris at onca.catsden.net chris at onca.catsden.net
Mon Feb 5 23:23:15 CET 2001


On Tue, 6 Feb 2001, Sam Wun wrote:

> Hi,
>
> Does anyone know what is the quickly way to sort a list of IP addresses?
>
> ie. 203.21.254.89 should be larger than 203.21.254.9

This may not be the fastest way, but it works, and its elegant :)

import string

def cmp_ipaddress ( ip1, ip2 ):
	parts1 = map(lambda x:int(x), string.split(ip1,'.'))
	parts2 = map(lambda x:int(x), string.split(ip2,'.'))
	comparisons = map ( lambda x,y: cmp(x,y), parts1, parts2 )
	return reduce ( lambda x,y: x or y, comparisons )

ips = [ '203.21.254.89', '203.21.254.9' ]

ips.sort ( cmp_ipaddress )

print `ips`

-> ['203.21.254.9', '203.21.254.89']


   ("`-/")_.-'"``-._        Ch'marr, a.k.a.
    . . `; -._    )-;-,_`)  Chris Cogdon <chmarr at furry.org.au>
   (v_,)'  _  )`-.\  ``-'
  _.- _..-_/ / ((.'       FC1.3: FFH3cmA+>++C++D++H++M++P++R++T+++WZ++Sm++
((,.-'   ((,/   fL               RLCT acl+++d++e+f+++h++i++++jp-sm++





More information about the Python-list mailing list