简体   繁体   English

如何使用try-except语句突破for循环?

[英]How to break out of this for loop with try-except statements?

I have a for loop with excerpts of try-except blocks referring to https://machinetalk.org/2019/03/29/neural-machine-translation-with-attention-mechanism/?unapproved=67&moderation-hash=ea8e5dcb97c8236f68291788fbd746a7#comment-67:- 我有一个带有try-except块摘录的for循环,该摘录引用了https://machinetalk.org/2019/03/29/neural-machine-translation-with-attention-mechanism/?unapproved=67&moderation-hash=ea8e5dcb97c8236f68291788fbd746a7#comment -67: -

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break

I want to come out of the loop and not execute the try block and leave everything and simply come out of both, the inner and outer loops as well as the entire try-except block. 我想退出循环而不执行try块并离开所有内容,而只退出内部和外部循环以及整个try-except块。 I don't know what is going wrong, as using the if condition in the inner/outer loop blocks doesn't work. 我不知道出了什么问题,因为在内部/外部循环块中使用if条件不起作用。

It may be a problem with nested loops, as covered by this answer . 本答案所述,嵌套循环可能是一个问题。 They suggest using return , but then your loop would need to be written as a function. 他们建议使用return ,但是您的循环将需要作为一个函数编写。 If that doesn't appeal you could try using various levels of break statements as shown in some of the answers. 如果那没有吸引力,您可以尝试使用各种级别的break语句,如一些答案中所示。 Using the for, else construction ( explained here ), I think your code would look like the following 使用for,else结构( 在此进行说明 ),我认为您的代码将如下所示

for e in range(NUM_EPOCHS):
    en_initial_states = encoder.init_states(BATCH_SIZE)

    for batch, (source_seq, target_seq_in, target_seq_out) in enumerate(dataset.take(-1)):
        loss = train_step(source_seq, target_seq_in,
                          target_seq_out, en_initial_states)

        if batch % 100 == 0:
                print('Epoch {} Batch {} Loss {:.4f}'.format(
                    e + 1, batch, loss.numpy()))


    try:
        test_target_text,net_words = predict()
    except Exception:
      continue

    if loss <=0.0001:
       break
else:
    continue ###executed if inner loop did NOT break
break  ###executed if inner loop DID break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM