22

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.

Here's the example:

import numpy
l = numpy.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 1]])
print(l[:,0:2].tolist())

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.

0

2 Answers 2

18

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.

Sign up to request clarification or add additional context in comments.

Comments

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 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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.