sorting on IP addresses
Jacob Kaplan-Moss
jacobkm at cats.ucsc.edu
Mon Feb 5 17:46:07 EST 2001
In article <3A7F26CB.BE85C96F at esec.com.au>, Sam Wun <swun at esec.com.au>
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
>
> Thanks
> Sam
>
Sam --
Not sure about quick, but this is the way I've been doing it. If any of
the gurus out there would like to point out a better method, I would be
happy to read it.
iplist = ["203.21.254.89",
"203.21.254.9",
"1.2.3.4",
"1.2.3.5",
"211.1.50.124",
"207.1.23.4",
"192.168.1.101",
"192.168.1.1"]
def ip_compare( a, b ):
"""a and b are valid IP addresses of the form w.x.y.z."""
la = [int(n) for n in a.split(".")]
lb = [int(n) for n in b.split(".")]
for pair in zip(la, lb):
if pair[0] > pair[1]:
return -1
elif pair[0] < pair[1]:
return 1
return 0
iplist.sort(ip_compare)
print iplist
Hope that helps,
Jacob
More information about the Python-list
mailing list