sorting on IP addresses

Mark Pilgrim f8dy at my-deja.com
Wed Feb 7 09:29:59 EST 2001


In article <mailman.981535000.18754.python-list at python.org>,
  =?iso-8859-1?Q?Max_M=F8ller_Rasmussen?= <maxm at normik.dk> wrote:
> it probably doesn't get any quikclier than this:
>
> -----------------------------------
>
> from string import split, join
>
> ips = """
> 192.168.1.1
> 192.168.1.2
> 192.168.1.3
> 192.169.1.5
> 127.1.2.3
> 192.167.1.6
> 191.168.1.4
> 193.168.1.2
> 127.1.1.1
> 194.168.1.8
> 195.168.1.2
> """
>
> ipList = split(ips, '\n')
>
> ipTupleList = []
> for ip in ipList:
>     if ip != '': # no empty lines
>         n1, n2, n3, n4 = tuple(split(ip, '.'))
>         ipTupleList.append((int(n1), int(n2), int(n3), int(n4)))
> ipTupleList.sort()
>
> for ipTuple in ipTupleList:
>     print "%s.%s.%s.%s" % ipTuple

Packing/unpacking the IP addresses via socket.inet_aton/inet_ntoa is
still faster, probably because more of the work is done in a natively
compiled module.

Timing test of various methods:
  http://deja.com/threadmsg_md.xp?AN=724795461.1

The above method takes 0.69 seconds on my machine to sort a list of
10000 IP addresses, whereas the pack/unpack method takes only 0.23
seconds.

-M
--
You're smart; why haven't you learned Python yet?
http://diveintopython.org/


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list