不确定python中for循环每次的结束位置。和C语言不一样,python的for循环没有括号()之类的约束,怎么看他的边界在哪里吖?是看他代码开头的空格是否与for对齐吗?
size = 100
theta0Vals = np.linspace(-10, 10, size)
# 前两个参数分别是数列的开头与结尾。第三个参数,表示数列的元素个数
theta1Vals = np.linspace(-1, 4, size)
JVals = np.zeros((size, size))
for i in range(size):
for j in range(size):
col = np.array([ [theta0Vals[i]], [theta1Vals[j]] ]).reshape(-1,1)
#不知道z的shape属性,想让z变成只有一列,行数管,
#通过`z.reshape(-1,1),Numpy自动计算出有16行
JVals[i,j] = compute_cost(X, y, col)
theta0Vals, theta1Vals = np.meshgrid(theta0Vals, theta1Vals)
# 产生一个以向量x为行,向量y为列的矩阵,
#X、Y必定是行数、列数相等的,且X、Y的行数都等
# 于输入参数y中元素的总个数,X、Y的列数都等于输入参数x中元素总个数;形成网格
JVals = JVals.T
print (JVals.shape, JVals[0, 0], JVals[1, 1] ) # test correct
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(theta0Vals, theta1Vals, JVals) # 绘制一个三维曲面
ax.set_xlabel(r'$\theta_0$')
ax.set_ylabel(r'$\theta_1$')
ax.set_zlabel(r'$J(\theta)$')
plt.show()
你想的没错,python是按照缩进排布
简单一个例子:
for i in range(10):
print(i)
a = 10 + i
for循环在 a = 10 + i的地方就已经结束了
是的。python是按照缩进排布,缩进后的代码相当于c中在外层打个大括号
层级缩进,不用纠结,左对齐就是了。
Python语言使用缩进,缩进的代码就是对应的语句的块
比如
for i in range(size):
这个循环就是
for j in range(size):
col = np.array([ [theta0Vals[i]], [theta1Vals[j]] ]).reshape(-1,1)
#不知道z的shape属性,想让z变成只有一列,行数管,
#通过`z.reshape(-1,1),Numpy自动计算出有16行
JVals[i,j] = compute_cost(X, y, col)
而
for j in range(size):
就是
col = np.array([ [theta0Vals[i]], [theta1Vals[j]] ]).reshape(-1,1)
#不知道z的shape属性,想让z变成只有一列,行数管,
#通过`z.reshape(-1,1),Numpy自动计算出有16行
JVals[i,j] = compute_cost(X, y, col)
另外,和C语言相比,python的for循环还有一个特殊的语法,叫做else
比如
""输出1——200的素数"""
import math
sum=0
print("100-200的素数:")
for i in range(1,200):
qrt=int(math.sqrt(i))
for j in range(2,qrt+1):
if i%j==0:
break
else: //注意看这里的else,可不是上面if的else,缩进写错了,它是for的 else,它在所有循环执行完,没有遇到break的时候运行
print(i)
sum+=1
print("素数数量为%d"%sum)
这个要特别掌握!