[英]How can I reduce the number of if statements in my 2D numpy code?
I have a numpy ndarray ( M
) holding a 2D symmetric matrix that contains N x N numbers (N is an integer), for example 我有一个numpy ndarray(
M
),其中包含一个包含N x N个数字(N是整数)的2D对称矩阵。
[[1. 2. 0. 0. 2. 2. 2.]
[2. 1. 2. 0. 0. 2. 2.]
[0. 2. 1. 2. 0. 0. 2.]
[0. 0. 2. 1. 2. 0. 0.]
[2. 0. 0. 2. 1. 2. 0.]
[2. 2. 0. 0. 2. 1. 2.]
[2. 2. 2. 0. 0. 2. 1.]]
I want to examine that: set item i,j in M to 0 where j in i+1, i+2, i+3 to zero in M 我想检查一下:将M中的项目i,j设置为0,将i + 1,i + 2,i + 3中的j设置为M中的零
I have this code, that do this: 我有这段代码,这样做:
for i in range(len(M)):
for j in range(len(M)):
if M[i, j] != 0:
if j == len(M) - 3:
M[i, j+2] = 0
M[i, j+1] = 0
elif j == len(M) - 2:
M[i, j+1] = 0
elif j == len(M) - 1:
continue
else:
M[i, j + 3] = 0
M[i, j + 2] = 0
M[i, j + 1] = 0
else:
continue
It works pretty well, but I want to reduce my if statements. 它工作得很好,但是我想减少我的if语句。 I read about
M[i,j:j+3]
, but I don't really know how to use it. 我读到有关
M[i,j:j+3]
,但我真的不知道如何使用它。
I'm waiting the following output matrix: 我正在等待以下输出矩阵:
[[1. 0. 0. 0. 2. 0. 0.]
[2. 0. 0. 0. 0. 2. 0.]
[0. 2. 0. 0. 0. 0. 2.]
[0. 0. 2. 0. 0. 0. 0.]
[2. 0. 0. 0. 1. 0. 0.]
[2. 0. 0. 0. 2. 0. 0.]
[2. 0. 0. 0. 0. 2. 0.]]
This should work: 这应该工作:
for i in range(len(M)):
for j in range(len(M)):
if M[i, j] != 0:
M[i, (j+1):(j+4)] = 0
print (M)
Output: 输出:
[[1. 0. 0. 0. 2. 0. 0.]
[2. 0. 0. 0. 0. 2. 0.]
[0. 2. 0. 0. 0. 0. 2.]
[0. 0. 2. 0. 0. 0. 0.]
[2. 0. 0. 0. 1. 0. 0.]
[2. 0. 0. 0. 2. 0. 0.]
[2. 0. 0. 0. 0. 2. 0.]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.