sorting on IP addresses

Alex Martelli aleaxit at yahoo.com
Wed Mar 7 09:29:54 CET 2001


"Justin Sheehy" <justin at iago.org> wrote in message
news:mailman.983939410.22287.python-list at python.org...
> Sam Wun <swun at esec.com.au> writes:
>
> > 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
>
> Convert to longs and sort on those values?
>
> Not all that quick, I suppose, but I don't know of a faster correct way.
>
> I suppose you could do it one octet at a time, which might be faster
> for cases like your example where the addresses are fairly close.
>
> The actual code for either of those approaches is short and
> straightforward.  Just write a little function to compare two
> addresses using the method of your choice, and pass it to your list's
> sort method.

...or, if the list is longish, use the decorate/sort/undecorate
design-pattern, which is faster for all but very short lists.

def sort_list_of_ips(list_of_ips):
    import socket
    temp = map(socket.inet_aton, list_of_ips)
    temp.sort()
    return map(socket.inet_ntoa, temp)

The full-fledged d/s/u pattern would append each item to its
sort-key, but we don't need it here since we can recover the
item's full information-content from the key itself.  Thus,
we can use the faster map for decoration and undecoration,
rather than list-comprehensions as are generally needed.


Alex






More information about the Python-list mailing list