Slicing NumPy array representing nested list
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 "sli开发者_Python百科ce from index 0
to 0,2
, incrementing by 2
" which makes no sense to me.
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.
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]]
精彩评论