Slicing Nested List

49,158

Solution 1

What you are doing is multi-axis slicing. Because l is a two dimensional array 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.

Solution 2

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)
>>> l
array([[0, 0, 0],
       [0, 1, 0],
       [1, 0, 0],
       [1, 1, 1]])
>>> print (l[:,0:2])
[[0 0]
 [0 1]
 [1 0]
 [1 1]]
>>> 

Solution 3

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 list
print (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]]
Share:
49,158
prelic
Author by

prelic

Software Engineer at CAE USA, Inc.

Updated on July 13, 2022

Comments

  • prelic
    prelic almost 2 years

    I'm familiar with slicing, I just can't wrap my head around this, and I've tried changing some of the values to try and illustrate what's going on, but it makes no sense to me.

    Anyway, here's the example:

    l = [[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]]  
    print l[:,0:2]
    

    Resulting in:

    [[0, 0], [0, 1] [1, 0], [1, 1]]
    

    I'm trying to translate this as "slice from index 0 to 0,2, incrementing by 2" which makes no sense to me.