Interesting (?) problem

mk mrkafk at gmail.com
Mon Jan 11 18:29:49 CET 2010


Hello everyone,

I have two lists of IP addresses:

hostips = [ 'a', 'b', 'c', 'd', 'e' ]

thread_results = [ 'd', 'b', 'c' ]

I need to sort thread_results in the same order as hostips.

(Obviously, hostips can contain any valid ip addresses as strings, they 
are sorted alphabetically here just for sake of example.)

Since explicit is better than implicit, I will clarify: thread_results 
is obviously result of threads communicating with IPs from hostips, and 
that can finish at various times, thus returning ips into thread_results 
in any order.

Sorting would be trivial to do if thread_results were not a subset of 
hostips (obviously, for some IPs communication can fail which excludes 
them from the result).

One approach I can see is constructing hostips_limited list that would 
contain only ips that are in thread_results but that would preserve 
order of hostips:

hostips_limited = []
for h in hostips:
     if h in thread_results:
         hostips_limited.append(h)

..and then doing sorting thread_results.

But maybe there is more elegant / faster approach?



Incidentally, it *seems* that list comprehension preserves order:

hostips_limited = [ h for h in hostips if h in thread_results ]

Empirically speaking it seems to work (I tested it on real ips), but 
please correct me if that's wrong.



Regards,
mk




More information about the Python-list mailing list