By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,403 Members | 1,089 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,403 IT Pros & Developers. It's quick & easy.

efficient list reduction

P: n/a
I have two lists. The values of the second list can be viewed as keys
for the first. I want to create a newlist based on the implied
mapping. The straight Python code would be:

newlist=[]
for key in keys:
newlist.append(oldlist[key])

What's the most efficient way of doing this? The best I could do was
the following list comprehension:

[oldlist[key] for key in keys]

Have I missed something?

Regards, A B Carter
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
A B Carter wrote:


I have two lists. The values of the second list can be viewed as keys
for the first. I want to create a newlist based on the implied
mapping. The straight Python code would be:

newlist=[]
for key in keys:
newlist.append(oldlist[key])

What's the most efficient way of doing this? The best I could do was
the following list comprehension:

[oldlist[key] for key in keys]

Have I missed something?

newlist = map(oldlist.__getitem__,keys)

Quite a bit faster for me.
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #2

P: n/a
gn********@aol.com (A B Carter) writes:
[oldlist[key] for key in keys]

Have I missed something?


If the keys and values are all characters or small positive ints,
maybe you can contort your program to let you use the very fast
string.translate operation. Otherwise, use psyco, and if your
listcomp is still not fast enough, write a C extension.
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.