A summary of answers questions

chris_barker at my-deja.com chris_barker at my-deja.com
Wed May 26 13:25:39 EDT 1999


Hi,

I got a lot of helpful replies to my questions. Here is a summary of the
useful ones.

> 1) loop a known number of times, without creating a list of indexes:
>
> for i in range(N):
> 	# do something

use xrange(N) instead.

> 2) Is there a "case" construct?

OOPS! Sorry about this, as it turns out I found this in the FAQ an hour
or so after posting.

There were some helpful suggestions, however, including:

dispatch = {
 'one':func_one,
 'two':func_two,
}

func_to_call = dispatch[ switch_variable ]
func_to_call()


> 3) lists of indexes:

Using the "take" function from NumPy does just what I wanted:

   from UserArray import take
   new_list = take(list,indices)

Note, this returns an array, but you can convert back to a list if need
be.   That would just be:

   new_list = take(list,indices).tolist()

NOTE: as it happens, I was using NumPy arrays anyway, so take was just
what I'm looking for. This is so useful, however, that I'd love to see
it added to the core language.

Some other options:

   new_list = map(lambda x: list[x], indexes)

Now this I like! clean, simple, and, I imagine, fast.

Here's the "obscure one-liner":

   import operator
   list = [1,2,3,4,5,6,7,8,9,10,11]
   indices = [3,5,9]
   new_list = map (operator.getitem, len (indices) * [list], indices)

This certainly works, but it builds a list that is
len(indices)*len(list) long, which could be pretty darn big, so it
doesn't seem like a very efficient way to go.


Thanks for everyone's input.

> -chris
>
> cbarker at jps.net
>
> --== Sent via Deja.com http://www.deja.com/ ==--
> ---Share what you know. Learn what you don't.---
>


--== Sent via Deja.com http://www.deja.com/ ==--
---Share what you know. Learn what you don't.---




More information about the Python-list mailing list