Python 中断但 return 或存储当前值
Python Break but return or store the current value
如何实现带有中断且 return中断处的值的 for 循环?
x = np.empty(1)
x[0] = 0.4
f = np.array([3,2,1,0,1,2,3])
y = np.empty(0)
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
else:
break
this returns y = [2,1,0] and x = [0.4,0.8,1.6,3.2] 但我希望它也 return 值 y = 1 and x = 6.4 这将是下一次迭代。
尝试这样的事情:
for i in range(len(f) - 1):
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
if f[i+1] > f[i]:
break
此代码段还将在跳出循环之前追加下一次迭代。
尝试像这样将代码添加到您的 else 块中:
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
else:
y = np.append(y,f[i+1])
x = np.append(x,newx)
break
这可能会锻炼。
只需添加一个新条件。
x = np.empty(1)
x[0] = 0.4
f = np.array([3,2,1,0,1,2,3])
y = np.empty(0)
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
elif f[i+1]>f[i] and f[i]==0:
newx = x[i] * 2
y = np.append(y, f[i + 1])
x = np.append(x, newx)
else:
break
如何实现带有中断且 return中断处的值的 for 循环?
x = np.empty(1)
x[0] = 0.4
f = np.array([3,2,1,0,1,2,3])
y = np.empty(0)
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
else:
break
this returns y = [2,1,0] and x = [0.4,0.8,1.6,3.2] 但我希望它也 return 值 y = 1 and x = 6.4 这将是下一次迭代。
尝试这样的事情:
for i in range(len(f) - 1):
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
if f[i+1] > f[i]:
break
此代码段还将在跳出循环之前追加下一次迭代。
尝试像这样将代码添加到您的 else 块中:
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
else:
y = np.append(y,f[i+1])
x = np.append(x,newx)
break
这可能会锻炼。
只需添加一个新条件。
x = np.empty(1)
x[0] = 0.4
f = np.array([3,2,1,0,1,2,3])
y = np.empty(0)
for i in range(len(f)):
if f[i+1] < f[i]:
newx = x[i]*2
y = np.append(y,f[i+1])
x = np.append(x,newx)
elif f[i+1]>f[i] and f[i]==0:
newx = x[i] * 2
y = np.append(y, f[i + 1])
x = np.append(x, newx)
else:
break