Slicing Nested List Slicing Nested List numpy numpy

Slicing Nested List


What you are doing is basically multi-axis slicing. Because l is a two dimensional list and you wish to slice the second dimension you use a comma to indicate the next dimension.

the , 0:2 selects the first two elements of the second dimension.

There's a really nice explanation here. I remember it clarifying things well when I first learned about it.


Works as said for me only if 'l' is a numpy array. For 'l' as regular list it raises an error (Python 3.6):

>>> l[[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]>>> print (l[:,0:2])Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: list indices must be integers or slices, not tuple>>> l=np.array(l)>>> larray([[0, 0, 0],       [0, 1, 0],       [1, 0, 0],       [1, 1, 1]])>>> print (l[:,0:2])[[0 0] [0 1] [1 0] [1 1]]>>> 


The following should work for ordinary lists. Assuming that it is a list of lists,and all the sublists are of the same length, then you can do this (python 2)

A = [[1, 2], [3, 4], [5, 6]]print (f"A = {A}")flatA = sum(A, [])     # Flattens the 2D listprint (f"flatA = {flatA}")len0 = len(A[0])lenall = len(flatA)B = [flatA[i:lenall:len0] for i in range(len0)] print (f"B = {B}")

Output will be:

A = [[1, 2], [3, 4], [5, 6]]flatA = [1, 2, 3, 4, 5, 6]B = [[1, 3, 5], [2, 4, 6]]