+ 3
Python - What does this code do?
X = [i for i in range(10)] r = slice(3, None) print(r) print(X[r][r][r])
2 ответов
+ 9
slice(x, y, z) equals x:y:z, but x:y:z can not be assigned to a variable.
r is just information for lists about how to be sliced.
X[r][r][r]
= X[slice(3, None)][slice(3, None)][slice(3, None)]
= X[3:None][3:None][3:None]
[x:None] equals [x:]
= X[3:][3:][3:]
Then it just gets sliced from left to right:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9][3:][3:][3:]
= [3, 4, 5, 6, 7, 8, 9][3:][3:]
= [6, 7, 8, 9][3:]
= [9]
Thus X[r][r][r] in the end would equal [9].
0
Actually you would not need to use nested slices.
You could use calculations to fit multiple slices into 1.
list[a:b:c][d:e:f][g:h:i]
= list[a+b+c : d-a + e-b + f-c : c * f * i]