efficient list reduction

Discussion in 'Python' started by A B Carter, May 11, 2004.

  1. A B Carter

    A B Carter Guest

    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
     
    A B Carter, May 11, 2004
    #1
    1. Advertising

  2. A B Carter

    Carl Banks Guest

    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
     
    Carl Banks, May 11, 2004
    #2
    1. Advertising

  3. A B Carter

    Paul Rubin Guest

    (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.
     
    Paul Rubin, May 11, 2004
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Patrick

    Bus reduction

    Patrick, Jun 7, 2004, in forum: VHDL
    Replies:
    1
    Views:
    563
    Egbert Molenkamp
    Jun 7, 2004
  2. Bryan Galvin

    NodeSet Reduction

    Bryan Galvin, Jun 9, 2004, in forum: XML
    Replies:
    3
    Views:
    423
    Bryan Galvin
    Jun 14, 2004
  3. Bryan Galvin
    Replies:
    2
    Views:
    432
    Bryan Galvin
    Sep 29, 2004
  4. ago
    Replies:
    11
    Views:
    690
    Anton Vredegoor
    Jan 20, 2006
  5. Philippe Martin

    image reduction script

    Philippe Martin, Mar 24, 2006, in forum: Python
    Replies:
    7
    Views:
    477
    Philippe Martin
    Mar 26, 2006
Loading...

Share This Page