Interesting (?) problem

M

mk

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
 
A

Arnaud Delobelle

mk said:
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.
[...solution:]
hostips_limited = []
for h in hostips:
if h in thread_results:
hostips_limited.append(h)

..and then doing sorting thread_results.

What do you mean by that last sentence?

[... or:]
Incidentally, it *seems* that list comprehension preserves order:

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

That's ok, but why not keep thread_results as a set instead of a list if
the ordering in that container is not significant but you are testing
membership a lot?
 
P

Paul Rubin

mk said:
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.

Assuming each address in hostips appears just once:

from itertools import izip,count
d = dict(izip(hostips, count()))
sorted_results = sorted(thread_results, key=d.get)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,965
Members
47,511
Latest member
svareza

Latest Threads

Top