我想在我的程序中做嵌套循环。但是,此代码不符合我的期望。
X=[0,1,1,1,0]
length=len(X)
for i,val in enumerate(X):
a=0
count=0
while (count<length):
a=15+a
print (a)
HWPQ=np.matrix([[1, 0, 0, 0], [0, math.cos(4*math.radians(a)),
math.sin(4*math.radians(a)), 0], [0, math.sin(4 * math.radians(a)), -
math.cos(4 * math.radians(a)), 0], [0, 0, 0, -1]])
result=HWPQ*val
print (result)
count=count +1
print ("\n")
应该在此程序中,我想使用循环为每个元素更新a
的值。例如:
X=0 for a=0
X=1 for a=15
X=1 for a=30
X=1 for a=45
X=0 for a=60
结果应该是我手动计算的结果:
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 1. 0. 0. 0. ]
[ 0. 0.5 0.8660254 0. ]
[ 0. 0.8660254 -0.5 0. ]
[ 0. 0. 0. -1. ]]
[[ 1. 0. 0. 0. ]
[ 0. -0.5 0.8660254 0. ]
[ 0. 0.8660254 0.5 0. ]
[ 0. 0. 0. -1. ]]
[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00 1.22464680e-16 0.00000000e+00]
[ 0.00000000e+00 1.22464680e-16 1.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -1.00000000e+00]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
答案 0 :(得分:1)
您的代码中似乎有很多不必要的变量,例如count
,X
和i
。删除它们并使用标准的for
循环,您将得到:
X=[0,1,1,1,0]
a=0
for val in X:
print (a)
HWPQ=np.matrix([
[1, 0, 0, 0],
[0, math.cos(4*math.radians(a)), math.sin(4*math.radians(a)), 0],
[0, math.sin(4 * math.radians(a)), - math.cos(4 * math.radians(a)), 0],
[0, 0, 0, -1]])
result=HWPQ*val
print (result)
a=15+a
print ("\n")
这将创建所需的输出。
0
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
15
[[ 1. 0. 0. 0. ]
[ 0. 0.5 0.8660254 0. ]
[ 0. 0.8660254 -0.5 0. ]
[ 0. 0. 0. -1. ]]
30
[[ 1. 0. 0. 0. ]
[ 0. -0.5 0.8660254 0. ]
[ 0. 0.8660254 0.5 0. ]
[ 0. 0. 0. -1. ]]
45
[[ 1.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 -1.00000000e+00 1.22464680e-16 0.00000000e+00]
[ 0.00000000e+00 1.22464680e-16 1.00000000e+00 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -1.00000000e+00]]
60
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]