【问题标题】:How can you go to the next word of a list on the previous loop in python? [duplicate]如何在 python 中的上一个循环中转到列表的下一个单词? [复制]
【发布时间】:2020-07-31 14:16:21
【问题描述】:

要在循环中转到下一个单词,您只需要使用 continue 函数即可。

例如

a = ['a', 'b', 'c', 'd']
for word in a:
    continue

但是如果代码是这样的:

a = ['a', 'b', 'c', 'd']
for word in a:
    for word2 in word:
        continue

continue 函数适用于第二个循环,但我想要一些适用于第一个循环并同时写入第二个循环的东西。

【问题讨论】:

  • 你想在这里做什么?
  • 没有继续功能。
  • 这能回答你的问题吗? How to break out of multiple loops?
  • 在那里使用break 而不是continue,这将继续外循环。

标签: python list loops continue


【解决方案1】:

您可以从内部循环中中断并使用 else 来确定外部循环是否应该继续。

a = ['aaaaxaaaa', 'bbbbbb', 'cccccxccc', 'ddddxddd']
for word in a:
    for letter in word:
        at_end=False
        if (letter == 'x'): break
        print(letter)
    else:    # only called at end of loop if no break
        at_end = True
    if (at_end == False): continue  # inner loop exited early
    print(word)

【讨论】:

    【解决方案2】:

    使用当前索引可帮助您在循环位置之外导航。枚举内置非常适合这个。

    a = ['a', 'b', 'c', 'd']
    l = len(a)
    for i, word in enumerate(a):
        nexti = i + 1
        nextword = a[nexti] if nexti <= l else None
        ...
    

    【讨论】:

      【解决方案3】:

      如果需要第二次继续,可以使用变量来阻止:

      a = ['a', 'b', 'c', 'd']
      for word in a:
          for word2 in word:
              do_continue = true # Defining the variable
              continue
          if do_continue:
              continue
      

      【讨论】:

      • 代码中好像有错别字。
      猜你喜欢
      • 2019-09-01
      • 1970-01-01
      • 2019-01-26
      • 2021-07-11
      • 2020-05-21
      • 1970-01-01
      • 2015-09-11
      • 2021-08-31
      • 2017-01-26
      相关资源
      最近更新 更多