efficient list reduction

A

A B Carter

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
 
C

Carl Banks

A said:
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.
 
P

Paul Rubin

[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.
 

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
473,731
Messages
2,569,432
Members
44,835
Latest member
KetoRushACVBuy

Latest Threads

Top