我想知道python基本功能中切片列表的时间复杂度
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])
这是我想要的结果
[[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
答案 0 :(得分:0)
对于第一个问题:
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])))
答案 1 :(得分:0)
Numpy使二维数组的垂直切片更加容易。但是,没有它,您可以获得相同的结果。假设我们有以下2D列表:
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]]
表示为以下矩阵:
[[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]]
假设您要对此进行切片以形成以下模式:
这可以通过以下方法实现,而无需使用numpy:
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)
如果我们改用numpy,则可以重新编写以下代码:
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])