sub-list extraction, logical indexation

P

Pierre

Hello Everyone,

I would like to know if it is possible to extract a sub-list from a
list ?

typically if :

L =[[1, 2, 3],[4, 5, 6],[3] ]

How to extract easily the elements 0 and 2 of L in order to get :

L2 =[[1, 2, 3],[3] ]

Moreover, I would like to know if it is possible to use logical
indexation such that :

index = [ True, False, True]
L2 = L

or usual indexation, something like
index=[0, 2]
L2 = L

I tried, but failed...
Thanks for your help

Pierre
 
D

Diez B. Roggisch

Pierre said:
Hello Everyone,

I would like to know if it is possible to extract a sub-list from a
list ?

typically if :

L =[[1, 2, 3],[4, 5, 6],[3] ]

How to extract easily the elements 0 and 2 of L in order to get :

L2 =[[1, 2, 3],[3] ]

Moreover, I would like to know if it is possible to use logical
indexation such that :

index = [ True, False, True]
L2 = L

or usual indexation, something like
index=[0, 2]
L2 = L

I tried, but failed...
Thanks for your help


index = [ True, False, True]
L2 = [v for i, v in enumerate(L) if index]

Diez
 
M

MRAB

Diez said:
Pierre said:
Hello Everyone,

I would like to know if it is possible to extract a sub-list from a
list ?

typically if :

L =[[1, 2, 3],[4, 5, 6],[3] ]

How to extract easily the elements 0 and 2 of L in order to get :

L2 =[[1, 2, 3],[3] ]

Moreover, I would like to know if it is possible to use logical
indexation such that :

index = [ True, False, True]
L2 = L

or usual indexation, something like
index=[0, 2]
L2 = L

I tried, but failed...
Thanks for your help


index = [ True, False, True]
L2 = [v for i, v in enumerate(L) if index]

Or:

L =[[1, 2, 3],[4, 5, 6],[3] ]
index = [ True, False, True]

from itertools import izip
L2 = [v for i, v in izip(index, L) if i]
 
T

Terry Reedy

Pierre said:
Hello Everyone,

I would like to know if it is possible to extract a sub-list from a
list ?

typically if :

L =[[1, 2, 3],[4, 5, 6],[3] ]

How to extract easily the elements 0 and 2 of L in order to get :

L2 =[[1, 2, 3],[3] ]

L2 = [L[0],L[2]]
Moreover, I would like to know if it is possible to use logical
indexation such that :

index = [ True, False, True]
L2 = L

use zip(index,L) in a for loop
or usual indexation, something like
index=[0, 2]
L2 = L

#untried
L2=[]
for i in index
L2.append(L)

tjr
 

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
474,183
Messages
2,570,968
Members
47,524
Latest member
ecomwebdesign

Latest Threads

Top