[英]why doesn't this stop running?
why is this code running like forever? 为什么这段代码永远运行? I want it to stop when all numbers in y_list are near to an integer as I defined in "def C(y)" 我希望当y_list中的所有数字都接近我在“ def C(y)”中定义的整数时停止
y_list=[1.0, 3.4 ]
k=1
def C(y):
return abs(y-round(y)) < 0.15
while not all(C(y) for y in y_list):
z_list = [y*k for y in y_list]
k+=1
print(z_list)
You aren't changing y_list
(and you don't want to change it!). 您不需要更改y_list
(并且您不想更改它!)。 And because you're testing the static y_list
in the while
loop condition, that loop will never end. 并且由于您正在while
循环条件下测试静态y_list
,因此该循环将永远不会结束。 But you are changing z_list
so you need to test that z_list
meets your condition. 但是您正在更改z_list
因此需要测试z_list
满足您的条件。
And so that the while
test doesn't fail on the first loop you need to make z_list
a copy of y_list
before the loop starts. 并且为了使while
测试不会在第一个循环上失败,您需要在循环开始之前将z_list
复制为y_list
。
y_list = [1.0, 3.4 ]
# Copy the original data
z_list = y_list[:]
def C(y):
return abs(y-round(y)) < 0.15
k = 1
while not all(C(y) for y in z_list):
z_list = [y*k for y in y_list]
k+=1
print(z_list)
output 产量
[1.0, 3.4]
[2.0, 6.8]
[3.0, 10.2]
[4.0, 13.6]
[5.0, 17.0]
Note that I made z_list
a copy of y_list
by doing 请注意,通过执行以下操作,我将z_list
复制为y_list
z_list = y_list[:]
If I just did 如果我只是做了
z_list = y_list
then z_list
would simply be another name for the same list object as y_list
, you wouldn't get two separate lists. 那么z_list
只是与y_list
相同的列表对象的另一个名称,您不会得到两个单独的列表。
FWIW, here's another way to write this. FWIW,这是另一种写法。 We use itertools.count
so we don't have to update k
manually, and map
to call the testing function, which I've given a more meaningful name. 我们使用itertools.count
因此我们不必手动更新k
并map
到调用测试函数,我给它起了一个更有意义的名称。
from itertools import count
y_list = [1.0, 3.4 ]
z_list = y_list[:]
def almost_int(y):
return abs(y - round(y)) < 0.15
for k in count(2):
print(z_list)
if all(map(almost_int, z_list)):
break
z_list = [y*k for y in y_list]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.