根据已回答的解决方案,我测试了循环。我希望范围从6到10; 11到16,所以一直到条件满足,但循环保持从1到5运行。
set_mean = -10
#calculated_mean = None
energy = []
calculated_mean = float('inf')
while calculated_mean > set_mean:
for i in range(1, 5):
energy.append(i-i*i)
print(energy)
calculated_mean = sum(energy[-2:])/2
print(calculated_mean)
如何自动化范围,以便在第二个循环中切换到下五个值,如果条件不满足则依此类推。对于此示例,如果循环将从6运行到10,则它将满足。 谢谢!
答案 0 :(得分:3)
假设您只是要求以动态方式使用以下内容:
set_mean = -10
#calculated_mean = None
energy = []
calculated_mean = float('inf')
x = 1
while calculated_mean > set_mean:
for i in range(x, x+4): # you can change step size here by passing it as last argument
energy.append(i-i*i)
print(energy)
calculated_mean = sum(energy[-2:])/2
print(calculated_mean)
x = x + 1
输出为:
[0]
0
[0, -2]
-1
[0, -2, -6]
-4
[0, -2, -6, -12]
-9
[0, -2, -6, -12, -2]
-7
[0, -2, -6, -12, -2, -6]
-4
[0, -2, -6, -12, -2, -6, -12]
-9
[0, -2, -6, -12, -2, -6, -12, -20]
-16
我认为这正是你想要的。因为当你获得 -16
时,循环会停止答案 1 :(得分:-1)
我没有看到任何条件,因为 calculated_mean 将始终大于 set_mean ,所以此循环将在您当前版本中永久运行,因为您正在制作每次进入循环时,能量列出的更大,我真的不明白你的条件是什么"对于calculate_mean,但如果它只是列表中最后2个数字的平均值,它将永远不会大于你的set_mean,这将导致无限循环。