2
  1. What I wanna process is slice 2D array partially without numpy module like following example with numpy.
  2. and I want to know Time Complexity of Slicing Lists in python basic function

    import numpy as np    
    A = np.array([ [1,2,3,4,5,6,7,8] for i in range(8)])
    n = len(A[0])
    x = int(n/2)
    
    TEMP = [[None]*2 for i in range(2)]
    
    for w in range(2):
        for q in range(2):
            TEMP[w][q] = A[w*x:w*x+x,q*x:q*x+x]
    
    for w in range(2):
        for q in range(2):
            print(TEMP[w][q])
    

here is the result that i wanna get

[[1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]]
[[5 6 7 8]
 [5 6 7 8]
 [5 6 7 8]
 [5 6 7 8]]
[[1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]
 [1 2 3 4]]
[[5 6 7 8]
 [5 6 7 8]
 [5 6 7 8]
 [5 6 7 8]]

Process finished with exit code 0

2 Answers 2

1

For the first question:

A = [ [1,2,3,4,5,6,7,8] for i in range(8)]
n = len(A[0])
x = int(n/2)

TEMP = [[None]*2 for i in range(2)]

for w in range(2):
    for q in range(2):
        TEMP[w][q] = [item[q * x:(q * x) + x] for item in A[w * x:(w * x) + x]]

for w in range(2):
    for q in range(2):
        print("{i}, {j}: {item}".format(i=w, j=q, item=repr(TEMP[w][q])))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your answer
0

Numpy makes the vertical slicing of 2 dimensional array easier. However, you can achieve the same results without it. Imagine if we have the following 2D list:

arr1=[[1,1,1,0,0,0],[0,1,0,0,0,0],[1,1,1,0,0,0],[0,0,2,4,4,0],[0,0,0,2,0,0],[0,0,1,2,4,0]]

which is represented as the following matrix:

[[1, 1, 1, 0, 0, 0],
 [0, 1, 0, 0, 0, 0],
 [1, 1, 1, 0, 0, 0],
 [0, 0, 2, 4, 4, 0],
 [0, 0, 0, 2, 0, 0],
 [0, 0, 1, 2, 4, 0]]

Let's say that you want to slice this to form the pattern below :

enter image description here

This can be achieved without numpy by the following :

for x in range (0,4):
        for y in range (0,4):
            # Here we traverse through the 2D array vertically
            temp_matrix= arr1[x][y:y+3],arr1[x+1][y:y+3],arr1[x+2][y:y+3]
             print (temp_matrix) 

If we use numpy instead we can re-write the following code :

arr=np.array(arr1)
rows = arr.shape[0]
cols = arr.shape[1]
for x in range (0,rows-2):
    for y in range (0, cols-2):
        print(arr[x:x+3,y:y+3])

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.