[英]Why won't this go back to the beginning of the while loop?
我正在尝试创建一个花名册,作为创建过程的一部分,代码会遍历多个循环,创建几个花名册,将它们相互比较以获得“理想”,然后吐出“最理想/最差”的结尾。
下面的部分是我试图检查在某一天是否有人被分配的班次太接近代码“工作”的日期,如果是这样,他们应该从可用个人列表中删除,并且代码应该 go 回到 while 循环的开头。
我尝试将continue
移动到各个点,创建了大量无限循环(叹气),但我似乎无法从whocando[r][3]
中的缩短列表中进行选择的过程发生。 如果我在 Ruby 我会使用redo
,但我无法让它工作。
solution_found = False
whocando = [
[date(2018, 1, 2), 'Tuesday', 1,
['XX', 'BB', 'UU', 'MM', 'GG'], ['PP', 'VV']],
[date(2018, 1, 3), 'Wednesday', 1,
['UU', 'SS', 'NN', 'BB', 'GG'], ['HH', 'AA', 'FF', 'KK', 'QQ', 'TT']],
[date(2018, 1, 4), 'Thursday', 1,
['AA', 'RR', 'MM', 'KK', 'BB', 'UU', 'QQ'], ['CC', 'HH', 'NN', 'XX', 'JJ']]
]
r = random.randrange(0,len(whocando))
while whocando[r][3] and not solution_found:
chosenone = random.choice(whocando[r][3])
# next bit iterates over a list of shifts already filled,
# creates a list of dates and calls a function that compares the dates
# with the current date to see if the two shifts are too close together
checker = [k for k,v in interim_rota.items() if v == chosenone]
for shift in checker:
q = daysprox(working_date,shift)
# daysprox() returns a tuple of (True, proxtype), where proxtype
# is an integer, if shifts are too close together
if q[0]:
this_iteration.too_close_by_func += 1
try:
whocando[r][3].remove(chosenone)
continue
# now I expect the while loop to start again and find a
# new choseone, but it doesn't, it proceeds into the next
# section of the code and adds the current choseone to
# the rota
except ValueError:
traceback_output = traceback.format_exc()
print(traceback_output, whocando[r][3], chosenone)
else:
solution_found = True
回答: 发现在这段代码之外有一些循环嵌套......
我不确定我是否理解 100%,但如果你想退出 for 循环,你可能想使用break
而不是continue
。 例如:
>>> i = 0
>>> while i < 2:
... print(i)
... for s in "test":
... if s == "s":
... break
... print(s)
... i += 1
...
0
t
e
1
t
e
不喜欢这样做,也许带有标志的while
循环在流程中可能更容易和更容易理解。 但这只是个人意见:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.