Extracting an undefined number of items from a list

Chris Rebert clp2 at rebertia.com
Mon Apr 12 16:18:58 EDT 2010


On Mon, Apr 12, 2010 at 1:05 PM, vsoler <vicente.soler at gmail.com> wrote:
> Hi everyone,
>
> say that 'db' is a list of values
> say 'i' is a list of indexes
> I'd like to get a list where each item is i-th element of db.
>
> For example:
>
> db=[10,20,30,40,50,60,70,80,90]      #undefined length
> i=[3,5,7]                                         #undefined length
> then result=[30,50,70]                     # resulting list
>
> how can I do this?

result = [db[k-1] for k in i] # your indices seem to be 1-based

See "List comprehensions":
http://docs.python.org/tutorial/datastructures.html#list-comprehensions

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list