-I want to make array initialization compact-
That wish can be realized. Yes, it's 3.8 ~.
(Variable name:=Definition)[slice] =Change
Note) Even if you do not slice, an error will be thrown if you do not add [:]
etc.
For example
** ~ I want to define a matrix in which 1 to 9 are lined up diagonally plus 1 every 3 rows ~ **
Such a mysterious situation is also this street
import numpy as np
(x:=np.diag(range(10)))[::3] += 1
x
out
array([[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 2, 0, 0, 0, 0, 0, 0, 0],
[ 1, 1, 1, 4, 1, 1, 1, 1, 1, 1],
[ 0, 0, 0, 0, 4, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 5, 0, 0, 0, 0],
[ 1, 1, 1, 1, 1, 1, 7, 1, 1, 1],
[ 0, 0, 0, 0, 0, 0, 0, 7, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 8, 0],
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 10]])
For example
** ~ I want to draw a matrix with my left and right inverted on a square matrix with 1 to 9 lined up diagonally ~ **
Even in such a case, this street
import numpy as np
(x:=np.diag(range(10)))[:] -= x[:, ::-1]
x
out
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 0, 0, 0, 0, 0, 0, -1, 0],
[ 0, 0, 2, 0, 0, 0, 0, -2, 0, 0],
[ 0, 0, 0, 3, 0, 0, -3, 0, 0, 0],
[ 0, 0, 0, 0, 4, -4, 0, 0, 0, 0],
[ 0, 0, 0, 0, -5, 5, 0, 0, 0, 0],
[ 0, 0, 0, -6, 0, 0, 6, 0, 0, 0],
[ 0, 0, -7, 0, 0, 0, 0, 7, 0, 0],
[ 0, -8, 0, 0, 0, 0, 0, 0, 8, 0],
[-9, 0, 0, 0, 0, 0, 0, 0, 0, 9]])
The number of convenient walrus operator utilization series is increasing ...
Recommended Posts