efficient list reduction

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • A B Carter

    efficient list reduction

    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
  • Carl Banks

    #2
    Re: efficient list reduction

    A B Carter wrote:[color=blue]
    >
    >
    > 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?[/color]


    newlist = map(oldlist.__g etitem__,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

    Comment

    • Paul Rubin

      #3
      Re: efficient list reduction

      gnosticray@aol. com (A B Carter) writes:[color=blue]
      > [oldlist[key] for key in keys]
      >
      > Have I missed something?[/color]

      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.translat e operation. Otherwise, use psyco, and if your
      listcomp is still not fast enough, write a C extension.

      Comment

      Working...